3

I'm using the following function to upload a file to a server with the HttpClient of angular 7

  pushFileToStorage(productId, key, file: File): Observable<any> {
    let formdata: FormData = new FormData();

    formdata.append('prod', file);
    let url_ = '/admin5/api/v1/product/images/upload?';
    url_ += "productId=" + encodeURIComponent("" + productId) + "&";
    url_ += "kind=" + encodeURIComponent("" + key);

    return this.http.post(url_,formdata);
  }

The problem I'm having is that the HttpClient sets the wrong content type header (application/json instead of "multipart/form-data") and so the server can't read the file. This is what I see on the developer tools

enter image description here

enter image description here

Any idea on what I'm doing wrong? Thanks

Maurizio Pozzobon
  • 3,044
  • 7
  • 34
  • 44

3 Answers3

13

I just found out that the project I'm working on has an HttpInterceptor that is adding a content-type "application/json" by default to any request that doesn't set the content type. So that was the problem.

Maurizio Pozzobon
  • 3,044
  • 7
  • 34
  • 44
  • 1
    Thank you so much, this was exactly was what happening. – ecrb Jan 15 '20 at 11:36
  • Thank you for pointing me in the right direction. Three hours I just spent trying to figure out why files wouldn't upload, three hours I'll never get back and it's because I'd tried to be clever with a HttpInterceptor and was adding a Content-Type header. – wobblycogs Mar 19 '20 at 12:03
  • After 3 hour research I have found that post. And was exactly that problem. Thank you! – dbricman Oct 12 '21 at 22:18
2

In my case, I am using FormData also. The reason behind this was the HTTP interceptor as @Maurizio Pozzobon stated in the accepted answer. I am using HTTP Interceptor like below--

enter image description here

Here My interceptor send my token to every http call as

'Content-Type' : 'application/json; charset=utf-8'

Which was creating the wrong content type error. So I need to bypass the interceptor for this type of call. I follow from Here.

I import HttpBackend

enter image description here

Declare HttpClient variable

enter image description here

Declare in the Constructor

enter image description here

Now using this httpclient i request Post api call with formdata carring my file. This Http Post call bypass Http Interceptor. My problem solved this way.

Mohammad Sadiqur Rahman
  • 5,379
  • 7
  • 31
  • 45
  • could you please elaborate further how you solved your problem. I'm facing the same upload issue. ``System.InvalidOperationException: Incorrect Content-Type: application/json`` – carltonstith May 05 '21 at 05:17
0

This is the server header, and the server answers you using json and this is absolutely normal. It’s easier and faster to look for a library to load pictures like this https://www.npmjs.com/package/angular-file-uploader or https://www.npmjs.com/package/angular-file