简体   繁体   中英

Any work around to achieve the functionality of angular js uploading multipart/form data in angular ? How to set content type undefined in angular?

This is just a piece of working code in angular js that is used for uploading a file. Content type the browser detects : 'multipart/form-data; boundary=----WebKitFormBoundaryXPoOG8abcZmXOpiB' .

$http({
                method: "POST",
                url: url,
                transformRequest: angular.identity,
                headers: {
                    "Authorization": "Bearer " + getToken(),
                    "Content-Type": undefined,
                    "Impersonation": isImpersonation()
                },
                data: formData
            })

Now the same result I want to achieve in angular 11 but not able to set content-type:undefined. also could not find any option of transformRequest: angular.identity,

This is the piece of code I have written down in angular and not able to upload the image.

 return this.httpClient.post<TRsp>(url, formData, {
      headers: {
        "Authorization": "Bearer " + getToken(),
        "Content-Type": 'multipart/form-data',
      }
    }

Can anyone tell me how to convert the above angular js code to angular?

Setting Content-type invalidated your api request sometimes. So you need to do is that include empty headers in the request call.

HTML:

<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx">

TS:

fileChange(event) {
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
        let file: File = fileList[0];
        let formData:FormData = new FormData();
        formData.append('uploadFile', file, file.name);

        // Do not add content type in headers.
        let headers = new Headers({
          "Authorization": "Bearer " + getToken(),
        });            
        let options = new RequestOptions({ headers: headers });

        this.http.post(`${this.apiEndPoint}`, formData, options)
            .tap(data => console.log("do whatever you want with response data")
            .subscribe();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM