3

I am attempting to pass a file to Web API from an Angular 2 app, and the actual file data does not get sent.

Here is my angular 2 service code:

        var headers = new Headers();
        headers.append('Content-Type', 'multipart/form-data');

        var formData = new FormData();
        formData.append("file", file);

        return this.http.post('http://myapiurl.com/files/upload', formData, { headers: headers }).map(res => res.json());

In the angular 2 docs, the POST method signature is as follows:

post(url: string, body: string, options?: RequestOptionsArgs) : Observable<Response>

There is no option to pass Form Data, or other object. Just a string in the bodys request. The current work around is to use javascript and regular xhr requests. There are obvious downsides to this like not being able to use observables, etc.

Any help on this would be greatly appreciated.

aoakeson
  • 602
  • 1
  • 8
  • 20

3 Answers3

3

In fact, this isn't supported yet. See this in-progress issue: https://github.com/angular/angular/issues/5517.

The current implementation of the HTTP support only supports text contents for request payload. See these two files

Hope it helps you, Thierry

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
1

In the final version of angular 2, http.post(...) has the body parameter as any rather than string, doc here. So what you can do is simply pass the formData object, the way you were doing in the question.

irtaza
  • 721
  • 1
  • 6
  • 13
0

In my project , I use the XMLHttpRequest to send multipart/form-data. I think it will fit you to.

and the uploader code

let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://www.example.com/rest/api', true);
xhr.withCredentials = true;
xhr.send(formData);

html code

<input type="file" (change)="selectFile($event)">

ts code

selectFile($event): void {
  var inputValue = $event.target;
  this.file = inputValue.files[0];
  console.debug("Input File name: " + this.file.name + " type:" + this.file.size + " size:" + this.file.size);
}

upload code:

const URL = 'http://www.example.com/rest/upload/avatar'; 

uploader:MultipartUploader = new MultipartUploader({url: URL});

item:MultipartItem = new MultipartItem(this.uploader);

if (this.item == null){
   this.item = new MultipartItem(this.uploader);
}
if (this.item.formData == null)
  this.item.formData = new FormData();

this.item.formData.append("email",  this.email);
this.item.formData.append("password",  this.password);
this.item.formData.append("file",  this.file);

this.item.callback = this.uploadCallback;
this.item.upload();

Here is example : https://github.com/wangzilong/angular2-multipartForm

Zilong Wang
  • 564
  • 4
  • 14