Sebastian Olsen Sebastian Olsen - 6 months ago 130
TypeScript Question

How do you POST a FormData object in Angular 2?

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');

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
to "
" my server complains about the boundaries, if I remove the
header completely, my server complains that it "
" a supported media type.

So, how do you send FormData with angular2?


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.


You can use XMLHttpRequest Object directly, for that.

And don't forget to set the header

setRequestHeader("enctype", "multipart/form-data");

// IE bug Fixes for Cache issues
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Cache-Control", "no-store");
xhr.setRequestHeader("Pragma", "no-cache");

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