最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Upload file in angular2: Body (FormData) empty - Stack Overflow

programmeradmin1浏览0评论

I'm trying to upload a picture with Angular2 to my REST Service (Loopback). The Loopback service works (tested with Postman) and accepts files with the x-www-form-urlencoded header.

Here's a simplified service method that sends the POST request:

public uploadFile(url : string, file: File): Observable<any> {
  let headers: Headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');

  let formData = new FormData();
  formData.append('file', file);

  let options: RequestOptionsArgs = { headers: headers };

  return this.http.post(url, formData, options)
  .map((res: any) => (res.text() != "" ? res.json() : {}));
}

Note that I've set the header to application/x-www-form-urlencoded and send the formData containing the file in the body.

In Angular, up until the point where I http.post the request, the formData is populated with the file, the file content is present, everyting's fine:

Data before Request

But in the request, the body is an empty object {}:

Request

I assume, Angular is trying to do JSON.stringify(formData), at least, when I try this, I also get "{}" as output.

I've seen plenty of posts doing exactly the same (http.post(url, formData)). So what am I missing?

I'm trying to upload a picture with Angular2 to my REST Service (Loopback). The Loopback service works (tested with Postman) and accepts files with the x-www-form-urlencoded header.

Here's a simplified service method that sends the POST request:

public uploadFile(url : string, file: File): Observable<any> {
  let headers: Headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');

  let formData = new FormData();
  formData.append('file', file);

  let options: RequestOptionsArgs = { headers: headers };

  return this.http.post(url, formData, options)
  .map((res: any) => (res.text() != "" ? res.json() : {}));
}

Note that I've set the header to application/x-www-form-urlencoded and send the formData containing the file in the body.

In Angular, up until the point where I http.post the request, the formData is populated with the file, the file content is present, everyting's fine:

Data before Request

But in the request, the body is an empty object {}:

Request

I assume, Angular is trying to do JSON.stringify(formData), at least, when I try this, I also get "{}" as output.

I've seen plenty of posts doing exactly the same (http.post(url, formData)). So what am I missing?

Share Improve this question edited Jan 30, 2017 at 9:05 hirse 2,4121 gold badge23 silver badges25 bronze badges asked Jan 29, 2017 at 17:47 ChristophChristoph 2531 gold badge3 silver badges9 bronze badges 8
  • Did you try to give blob data to form? – Roman C Commented Jan 29, 2017 at 17:52
  • Strange. I recently created a Plunker to answer a similar question and as you can see, just POSTing formData works. AFAIK, Angular DOES NOT automatically JSON.stringify(formData). It will POST what you pass as is. – AngularChef Commented Jan 29, 2017 at 18:08
  • What is printed in the console? – Roman C Commented Jan 29, 2017 at 18:46
  • I have done this the same way also. Are you 100% sure you 'file' is set to something? – Ben Cameron Commented Jan 29, 2017 at 21:01
  • 1 @AngularFrance Thanks for the Plunker! I compared it with my code and watched the output and it was so similar, also all the data was set, real strange! I tried removing the options from the request, because I figured that's the only aspect that differs between our solutions. And now it works. The request is then with multipart/form-data but interestengly my Loopback service does not care. However, it's still a bit frustrating. Would like to know why it doesn't work with urlencoded – Christoph Commented Jan 29, 2017 at 21:20
 |  Show 3 more comments

4 Answers 4

Reset to default 8

Just remove headers.append('Content-Type', 'multipart/form-data'); can solve problem.

See here

2017-08-24

From this How to inspect FormData? SO answer and this MDN documentation outputing FormData in the console just results in a {}.

FormData can directly be used in a for ... of structure, instead of entries(): for (var p of myFormData) is equivalent to for (var p of myFormData.entries()).

There is another solution is to use base64 and convert it in back-end side: `

var reader = new FileReader();
    reader.readAsDataURL(file);
    let res;
    reader.onload = function () {
    let headers = new Headers();
    headers.append("Content-type","application/x-www-form-urlencoded");
    headers.append('Accept', 'application/json');
    let options = new RequestOptions({ headers: headers });
    return this.http.post(config.serverUrl+"/index.php",
      {
         "file":reader.result}, options)
         .toPromise()
         .then(this.extractData)
         .catch(this.handleError);
      }
    };
    reader.onerror = function (error) {
        console.log('Error: ', error);
    };`

In my case i used formData.set() instead of formData.append()

please see example below :

 UploadFile(fileToUpload: File): Observable<boolean> {
     const endpoint = 'api/image/upload';
     var formData = new FormData();
     formData.set('file', fileToUpload);
     return this._http
     .post(endpoint, formData)
     .map(() => { return true; })
     .catch((e) => this.handleError(e));
 }
发布评论

评论列表(0)

  1. 暂无评论