当我尝试使用angular / spring上传文件时,出现异常:org.springframework.web.multipart.MultipartException:当前请求不是一个多部分请求,但是当我使用邮递员尝试它时可以正常工作
我的代码:角形
upload.service.ts:
public save(file: File) {
this.headers.set('Content-Type', 'multipart/form-data');
const formdata: FormData = new FormData();
formdata.append('file', file);
return this.http.post(this.baseUrl + "upload", formdata, { headers:
this.headers }).map(resp => resp.json());
}
上传组件:
currentFileUpload: File;
constructor(private uploadService: UploadService) { }
ngOnInit() {
}
selectFile(event) {
this.currentFileUpload = event.target.files[0];
}
uploadFile() {
this.uploadService.save(this.currentFileUpload).subscribe(resp => {
console.log(resp);
},
err => {
console.log(err);
});
}
html代码:
<div class="custom-file">
<input type="file" (change)="selectFile($event)" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="customFile">choisissez un fichier (*pdf, *csv ,*docs)</label>
<button class="btn btn-danger" (click)="uploadFile()">Upload</button>
</div>
代码后端:
@PostMapping("/api/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
String name = file.getOriginalFilename();
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File("src/upload/"+name)));
stream.write(bytes);
stream.close();
return "You successfully uploaded " + name + " into " + name + "-uploaded !";
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name + " because the file was empty.";
}
}