我想使用 angular 6 上传文件并将其与 API 连接,但它采用默认类型 "application/json",我想将其更改为文件格式

I want to upload file using angular 6 and connect that with API, but its taking default type "application/json", i want to change that to file format

我是这样做的:

fileUpload(data){

      let headers = new HttpHeaders().set('file', data);
         headers.append('Content-Type', 'application/file');
      let file_upload =  {
        headers: headers,
      };

    console.log(data, "file upload")
    return this.httpClient.post('api/data_loader/file/', file_upload);
  }

错误

Unsupported media type "application/json" in request.

预期结果:我想将此默认媒体类型更改为文件格式。

注:我用的是Angular6.

需要使用表单数据才能上传文件。

const formData: FormData = new FormData();
formData.append('file', data, data.name); 
this.httpClient.post('api/data_loader/file/', formData);

我假设您的数据是 formData,如果不是,则在调用 httpClient 之前创建类似的表单数据....

const data= new FormData();
data.append('file', data);  //note that this data is file not json data...

如果您要发送 formData,那么下面的函数应该可以工作...

fileUpload(data){


          let headers = new Headers({ 
    });

//add any header if you need to for authentication 

return this.httpClient.post('api/data_loader/file/',data, headers);
}