typescript 在 angular2 中上传文件:Body (FormData) 为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41924012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Upload file in angular2: Body (FormData) empty
提问by Christoph
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.
我正在尝试将带有 Angular2 的图片上传到我的 REST 服务(环回)。Loopback 服务工作(用 Postman 测试)并接受带有 x-www-form-urlencoded 标头的文件。
Here's a simplified service method that sends the POST request:
这是发送 POST 请求的简化服务方法:
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.
请注意,我已将标头设置为 application/x-www-form-urlencoded 并在正文中发送包含该文件的 formData。
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:
在 Angular 中,直到我 http.post 请求为止,formData 填充了文件,文件内容存在,一切都很好:
But in the request, the body is an empty object {}:
但是在请求中,body 是一个空对象 {}:
I assume, Angular is trying to do JSON.stringify(formData), at least, when I try this, I also get "{}" as output.
我假设,Angular 正在尝试执行 JSON.stringify(formData),至少,当我尝试这样做时,我也会得到“{}”作为输出。
I've seen plenty of posts doing exactly the same (http.post(url, formData)). So what am I missing?
我已经看到很多帖子做的完全一样(http.post(url, formData))。那么我错过了什么?
回答by Belter
回答by sebnukem
From this How to inspect FormData?SO answer and this MDN documentationoutputing FormData
in the console just results in a {}
.
从这个如何检查 FormData?所以回答和在控制台中输出的这个MDN 文档FormData
只会产生一个{}
.
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())
.
FormData 可以直接用在for ... of
结构体中,而不是entries()
:for (var p of myFormData)
等价于for (var p of myFormData.entries())
.
回答by ET-TAOUSY Zouhair
There is another solution is to use base64 and convert it in back-end side: `
还有另一种解决方案是使用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);
};`
回答by Dimo
In my case i used formData.set() instead of formData.append()
就我而言,我使用了 formData。set() 而不是 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));
}