如何在Angular 2中发布FormData对象? [英] How do you POST a FormData object in Angular 2?
问题描述
我需要上传文件并发送一些json,我有这个功能:
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');
headers.delete("Content-Type");
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() }
}
})
}
我的问题是,如果将content-type
设置为"multipart/form-data
",我的服务器会抱怨边界,如果完全删除content-type
标头,我的服务器会抱怨它"text/plain
"是受支持的媒体类型.
My issue is, if I set the content-type
to "multipart/form-data
" my server complains about the boundaries, if I remove the content-type
header completely, my server complains that it "text/plain
" a supported media type.
那么,如何发送带有angular2的FormData?
So, how do you send FormData with angular2?
推荐答案
它是Angular2 Git存储库上的打开问题,并且还有一个请求请求等待被合并,希望很快被合并.
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.
或者,
为此,您可以直接使用 XMLHttpRequest 对象
You can use XMLHttpRequest Object directly, for that.
别忘了设置标题
xhr.setRequestHeader("enctype", "multipart/form-data");
// IE workaround for Cache issues
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Cache-Control", "no-store");
xhr.setRequestHeader("Pragma", "no-cache");
在您创建的XMLHttpRequest
上.
类似问题:
这篇关于如何在Angular 2中发布FormData对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!