Search code examples
angularhttpclientmultipartform-datacontent-type

Angular 10 HttpClient not setting correct Content-Type header


I'm simply trying to send a file to a backend with Angular 10.
In Postman the same requests works! And the Content-Type header is getting set to

multipart/form-data; boundary=--------------------------131632757107984585618022

But when I do the same with Angular it just sets Content-Type to be text/plain;charset=UTF-8 and I get the unknown content type: "text/plain;charset=UTF-8" error from the backend.

The only solution i've found is setting the Content-Type to undefined But this this does not work because of the Cannot read property 'length' of undefined at http.js:105 error.

My code:

upload(event: any) {
    const files = event.target.files;
    const formData: FormData = new FormData();
    for (const file of files) {
        formData.append('files', file, file.name);
    }
    return this.http.post(environment.API_URL + '/add', FormData)
    .toPromise()
    .then((res) => console.log(res))
    .catch((err) => console.log(err));
}

Solution

  • You have to pass your formData-object - this may only be a typo-issue?

    return this.http.post(environment.API_URL + '/add', formData);