Angular 2 - Post 文件到 Web API

Angular 2 - Post File to Web API

我正在尝试将文件从 Angular 2 应用程序传递到 Web API,但未发送实际文件数据。

这是我的 angular2 服务代码:

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

在angular2文档中,POST方法签名如下:

post(url: string, body: string, options?: RequestOptionsArgs) : Observable<Response>

没有传递表单数据的选项,或其他 object。只是身体请求中的一个字符串。当前的解决方法是使用 javascript 和常规的 xhr 请求。这有明显的缺点,比如不能使用可观察对象等。

如有任何帮助,我们将不胜感激。

事实上,这还不被支持。查看这个进行中的问题:https://github.com/angular/angular/issues/5517.

HTTP 支持的当前实现仅支持请求负载的文本内容。查看这两个文件

希望对你有帮助, 蒂埃里

在我的项目中,我使用 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();

示例如下:https://github.com/wangzilong/angular2-multipartForm

在 angular 2 的最终版本中,http.post(...)body 参数作为 any 而不是 string,doc here .所以你可以做的就是简单地传递 formData 对象,就像你在问题中所做的那样。