我在将多个文件从有角度的前端发送到spring-boot后端时遇到问题。我已经尝试过从堆栈到网络的所有内容,但找不到答案。这是我的代码:
角度: .ts文件:
submit(){
this.uploadedFiles = this.uploadedFiles.map(item => {
let formData = new FormData();
return formData.append('file',item,item.name);
});
this.service.postFile(this.uploadedFiles).subscribe(result => {
console.log(result);
})
}
this.uploadedFiles是否以某种形式未定义为FormData类型?
服务文件:
postFile(files: any): Observable<string>{
return this.http.post('/id/file', files, {responseType:'text'});
}
弹簧控制器:
@PostMapping(value = "/file")
private String newFile(@RequestBody List<MultipartFile> mf) {
return "error";
}
在调试器内部,MF列表为空。
主要问题是,对于1个文件(当我仅使用MultipartFile时),我的代码有效。
我正在使用带有自定义上传事件的PrimeNG的p文件上传。
答案 0 :(得分:0)
I think the problem is with you sending an Array of FormData
instances to postFile
since you're instantiating formData
again and again inside the map
.
Give this a try to see if this works:
submit() {
const formData = new FormData();
this.uploadedFiles = this.uploadedFiles.map(item => formData.append('file', item, item.name));
this.service.postFile(this.uploadedFiles).subscribe(result => console.log(result));
}
PS: I haven't tested this out but I feel it should work.
I think you're logging the formData
to the console like this:
console.log(files);
In your postFile
method.
OR:
console.log(formData);
In your Component.
What you should be doing instead is
console.log(formData.get('file'));