实际上,我正在使用带有Angular 2编码的接口的Spring REST API。
我的问题是我无法使用Angular 2上传文件。
我在Java中的Webresources是:
@RequestMapping(method = RequestMethod.POST, value = "/upload")
public String handleFileUpload(@RequestParam MultipartFile file) {
//Dosomething
}
当我通过带有Auth标头等的URL请求调用它时(它具有适用于Chrome的Advanced Rest Client扩展),它完全可以正常工作
证明:(在这种情况下,一切正常)
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
Spring配置文件和Pom依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2</version>
</dependency>
但是,当我尝试使用网络表单执行相同的操作时:
<input type="file" #files (change)="change(files)"/>
<pre>{{fileContents$|async}}</pre>
使用(change)方法:
change(file) {
let formData = new FormData();
formData.append("file", file);
console.log(formData);
let headers = new Headers({
'Authorization': 'Bearer ' + this.token,
'Content-Type': 'multipart/form-data'
});
this.http.post(this.url, formData, {headers}).map(res => res.json()).subscribe((data) => console.log(data));
/*
Observable.fromPromise(fetch(this.url,
{method: 'post', body: formData},
{headers: this.headers}
)).subscribe(()=>console.log('done'));
*/
}
我的Web服务向我返回错误500,并在tomcat日志中显示该错误:http : //pastebin.com/PGdcFUQb
我也尝试过该'Content-Type': undefined
方法,但没有成功(在这种情况下,Web服务向我返回415错误。
有人可以帮助我找出问题所在吗?
问题已解决,我将在稍后用我的代码更新该问题:),但是,请看一下它工作得很好的插件。谢谢。
在最终版本中,这实际上很容易做到。花了我一些时间来解决这个问题,因为我遇到的有关它的大多数信息都已过时。如果其他人为此感到困扰,请在此处发布我的解决方案。
import { Component, ElementRef, Input, ViewChild } from '@angular/core';
import { Http } from '@angular/http';
@Component({
selector: 'file-upload',
template: '<input type="file" [multiple]="multiple" #fileInput>'
})
export class FileUploadComponent {
@Input() multiple: boolean = false;
@ViewChild('fileInput') inputEl: ElementRef;
constructor(private http: Http) {}
upload() {
let inputEl: HTMLInputElement = this.inputEl.nativeElement;
let fileCount: number = inputEl.files.length;
let formData = new FormData();
if (fileCount > 0) { // a file was selected
for (let i = 0; i < fileCount; i++) {
formData.append('file[]', inputEl.files.item(i));
}
this.http
.post('http://your.upload.url', formData)
// do whatever you do...
// subscribe to observable to listen for response
}
}
}
然后像这样使用它:
<file-upload #fu (change)="fu.upload()" [multiple]="true"></file-upload>
这就是全部。
或者,捕获事件对象并从srcElement获取文件。老实说,不确定是否有任何方法比其他方法更好!
请记住,FormData是IE10 +,因此,如果必须支持IE9,则需要使用polyfill。
更新2017-01-07
更新了代码以能够处理多个文件的上载。另外,我最初的答案缺少有关FormData的相当关键的一点(因为我将实际的上载逻辑移到了我在自己的应用程序中处理的单独服务中)。
当然!但是,当您搜索“角度2文件上传”时,这个问题是Google上出现的第一个问题。想通了,我会添加一些最新信息。
您使用的是什么版本的RC?有没有其他人成功使用过此工具?似乎不适合我。
好的,我有点困惑,文件上传似乎可以正常工作,但是很奇怪的是,由于我使用localhost:3000运行,因此上载无法找到上载文件夹(也许是由于路由?),而当我只链接本地主机/文件夹时我对此有任何错误的想法吗?
如果其他人想知道FormData的来源,那么它是本机的FormData对象:developer.mozilla.org/en-US/docs/Web/API/FormData/FormData您不需要导入任何东西。
这很棒!一个警告-确保不要手动设置Content-Type标头。不用说,Angular 2似乎至少在application / json和multipart / form-data之间选择正确的值