问题
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
Any idea on what I'm doing wrong? Thanks
回答1:
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.
回答2:
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
回答3:
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--
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
Declare HttpClient variable
Declare in the Constructor
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.
来源:https://stackoverflow.com/questions/58015254/angular-post-request-with-a-multipart-form-has-wrong-content-type