我尝试使用angular 4和spring框架进行文件上传工作,我已经实现了以下代码,但它不起作用。
angular component.ts
upload() {
let inputEl: HTMLInputElement = this.inputEl.nativeElement;
let fileCount: number = inputEl.files.length;
let formData = new FormData();
if (fileCount > 0) {
for (let i = 0; i < fileCount; i++) {
formData.append('file[]', inputEl.files.item(i));
}
console.log(fileCount);// print count of files correctly
this.http.post("/filestorage/api/upload", formData)
.map(res => res.json())
.subscribe();
}
}
弹簧控制器
@PostMapping("/upload")
@Timed
public void upload(@RequestParam(value="file", required=false)
MultipartFile file) throws IOException {
System.out.println(file); //get null value
}
答案 0 :(得分:0)
我已将MultipartFile更改为MultipartHttpServletRequest并进行了必要的更改,现在它可以正常工作。
@PostMapping("/upload")
@Time
public void upload(MultipartHttpServletRequest request) throws IOException {
Iterator<String> itr = request.getFileNames();
MultipartFile multipart = request.getFile(itr.next());
java.io.File convFile = new java.io.File( multipart.getOriginalFilename());
convFile.createNewFile();
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(multipart.getBytes());
fos.close();
}
答案 1 :(得分:0)
在您的上传功能中,请尝试将标题添加到您的请求中,例如:
upload() {
let inputEl: HTMLInputElement = this.inputEl.nativeElement;
let fileCount: number = inputEl.files.length;
let formData = new FormData();
if (fileCount > 0) {
for (let i = 0; i < fileCount; i++) {
formData.append('file[]', inputEl.files.item(i));
}
console.log(fileCount);// print count of files correctly
let headers = new Headers();// import { Headers,BaseRequestOptions } from '@angular/http';
headers.append('enctype','multipart/form-data');
headers.append('Accept', 'application/json');
let options = new BaseRequestOptions();
options.headers = headers;
this.http.post("/filestorage/api/upload", formData , options)
.map(res => res.json())
.subscribe();
}
}
使用Angular 4进行测试。