我无法从Angular UI向Spring Boot Backend发送数据和图像。
我的HTML:
<input type="file" (change)="onFileSelected($event)">
<button type="button" (click)="onUpload()" class="file-input">sdadsa</button>
我的组件
selectedFile:File = null;
onFileSelected(event) {
this.selectedFile = <File>event.target.files[0];
}
onUpload() {
const fb = new FormData();
const data = new CategoryModel("s", "s", "s", 1);
fb.append('image', this.selectedFile, this.selectedFile.name);
this.data.storeProduct(data, fb).subscribe(data => {
console.log(data)
})
}
我的服务:
/** POST Product on server */
storeProduct(category: CategoryModel, fd: FormData): Observable<any> {
return this.http.post(this.cateogryUrl, { category, fd }).pipe(
catchError(this.handleError<CategoryModel>('addHero'))
)
}
最后是我的Spring Boot方法:
@PostMapping
@ResponseStatus(HttpStatus.OK)
public void create(@RequestBody CategoryModel bike, @RequestParam("file") MultipartFile file) {
String fileName = fileStorageService.storeFile(file);
bike.setImagePath(fileName);
categoryRepository.save(bike);
}
发送数据时出现此错误:
org.springframework.web.multipart.MultipartException: Current request is not a multipart request
答案 0 :(得分:1)
在您的http请求标头中添加'enctype': 'multipart/form-data'
。
var headers = new Headers();
headers.append('enctype', 'multipart/form-data' );
// HTTP POST using these headers
this.http.post(url, data, {headers: headers});