Upload file in angular2: Body (FormData) empty

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?


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()) .


还有另一种解决方案是使用base64并将其转换为后端:`

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);
    };`
链接地址: http://www.djcxy.com/p/94858.html

上一篇: 将文件和目录添加到特定的子目录

下一篇: 将angular2:Body(FormData)中的文件上传为空