spring – 使用Angular2到REST API的文件上传
作者:互联网
实际上,我正在使用一个以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>
但是,当我尝试使用webform执行相同的操作时:
<input type="file" #files (change)="change(files)"/>
<pre>{{fileContents$|async}}</pre>
使用(更改)方法:
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’:未定义的方法,但没有成功(在这种情况下,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的相当重要的一点(因为我将实际的上传逻辑移动到我自己的应用程序中的一个单独的服务,我在那里处理它).
标签:angular2-http,angular,spring,spring-mvc,angular2-forms 来源: https://codeday.me/bug/20190917/1809657.html