我正在尝试从Angular 2应用程序将文件传递给Web API,并且不会发送实际的文件数据。
这是我的角度2服务代码:
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());
在angular 2 docs中,POST方法签名如下:
post(url: string, body: string, options?: RequestOptionsArgs) : Observable<Response>
没有选项可以传递表单数据或其他对象。只是身体要求中的一个字符串。目前的解决方法是使用javascript和常规xhr请求。这有明显的缺点,就是不能使用可观察量等。
对此的任何帮助将不胜感激。
答案 0 :(得分:3)
事实上,这还不支持。请参阅此正在进行的问题:https://github.com/angular/angular/issues/5517。
HTTP支持的当前实现仅支持请求有效负载的文本内容。请参阅这两个文件
希望它可以帮到你, 亨利
答案 1 :(得分:1)
在角度2的最终版本中,http.post(...)
的{{1}}参数为body
而不是any
,文档here。所以你可以做的只是传递string
对象,就像你在问题中所做的那样。
答案 2 :(得分:0)
在我的项目中,我使用XMLHttpRequest发送multipart / form-data。 我认为它适合你。
和uploader代码
let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://www.example.com/rest/api', true);
xhr.withCredentials = true;
xhr.send(formData);
html代码
<input type="file" (change)="selectFile($event)">
ts代码
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);
}
上传代码:
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();