I need to upload a file and send some json along with it, I have this function:
POST_formData(url, data) {
var headers = new Headers(), authtoken = localStorage.getItem('authtoken');
if (authtoken) {
headers.append("Authorization", 'Token ' + authtoken)
}
headers.append("Accept", 'application/json');
headers.delete("Content-Type");
var requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: this.apiURL + url,
headers: headers,
body: data
})
return this.http.request(new Request(requestoptions))
.map((res: Response) => {
if (res) {
return { status: res.status, json: res.json() }
}
})
}
My issue is, if I set the content-type
to "multipart/form-data
" my server complains about the boundaries, if I remove the content-type
header completely, my server complains that it "text/plain
" a supported media type.
So, how do you send FormData with angular2?
I solved this problem, don't need
content-type
at all.See here, https://stackoverflow.com/a/45879409/2803344
Also see here to check how to set
headers
, Angular2 - set headers for every request2017.8.25
It's an Open Isuue on Angular2 Git Repository, and there is also a Pull Request waiting to be merged, hope that it will be merged soon.
Alternatively,
You can use XMLHttpRequest Object directly, for that.
And don't forget to set the header
on the
XMLHttpRequest
that you make.Similar Questions:
How to upload file in Angular2
Angular 2 File upload from input type=file
Angular2 post uploaded file
Template:
UPD: Angular 5 - HttpClient + Typescript
old Http lib - before Angular 4.3:
I know this has been marked answered and is pretty old, however I had an issue posting the FormData object to an OpenIdConnect AuthServer, and the file upload examples above weren't what I was looking for.
Here is my service that gets an OpenIdAuthToken: