GeForce RTX 4090
GeForce RTX 4090

Reputation: 3498

Can't upload image using Angular's HttpClient

I am able to upload an image perfectly fine using the native fetch POST:

let formData = new FormData();
        formData.append('file', event.target.files[0]);
        console.log(event.target.files[0]);
        fetch('http://localhost:8080/file/upload', {
            method: 'POST',
            headers:{
                'Authorization': 'Bearer ' + JWT
            },
            body:formData
        }).then(response => console.log(response));

However, when I try this using Angular's HttpClient, the request fails since the 'Content-Type': 'multipart/form-data' is not added.

My Angular code:

The file where I'm calling the service:

this.fileSaverService.uploadImage(event.target.files[0]).subscribe(
            (data)=>{
                console.log(data);
            },
            (error) => {
                console.log(error);
            }
        );

The fileSaverService:

  uploadImage(fileToUpload) {
    const endpoint = 'http://localhost:8080/file/upload';
    const formData: FormData = new FormData();
    formData.append('file', fileToUpload);
    return this.api
      .post(endpoint, formData, { headers: {'Content-Type': 'multipart/form-data'} });
}

The this.api:

  post(endpoint: string, body: any, reqOpts: any = {}) {    
    reqOpts.headers = this.handleHeaders(reqOpts.headers);
    return this.http.post(endpoint, JSON.stringify(body), reqOpts);
  }

If I add the header manually when using HttpClient, I get this header without the boundary:

enter image description here

However the native fetch adds this header automatically with the boundary if I don't specify a header and this works perfectly:

Conent type with native fetch

What are my options here?

Upvotes: 1

Views: 1735

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93043

There are two problems with the code in your question:

  1. By setting Content-Type to multipart/form-data yourself, the serialisation of your FormData will not result in the correct header with boundaries being set behind the scenes.
  2. In your post function, you have JSON.stringify(body), which is converting your FormData object into a JSON string. After doing this, you're simply attempting to POST a string rather than a complete FormData object.

Upvotes: 1

Related Questions