我正在尝试将文件从 Angular 版本 (13.3.8)、Primeng (13.2.1) 作为多部分文件上传到 Spring Boot,但我无法在 post 方法中获取该文件(状态:415,错误:'不支持的媒体类型')
文件上传组件
<p-card header="Import file">
<p-fileUpload
customUpload="true"
(uploadHandler)="onUpload($event)"
[multiple]="false"
accept=".stk">
</p-fileUpload>
</p-card>
组件.ts
onUpload(event):any {
if (event.files.length === 0) {
return;
}
const file = event.files[0];
this.service.importFile(file).subscribe(
(response) => {
// Handle success response
console.log(response);
},
(error) => {
// Handle error response
console.error(error);
}
);
}
服务
importFile(file: File) : Observable<any>{
const formData: FormData = new FormData();
formData.append('file', file, file.name);
const headers = new HttpHeaders();
//this is the important step. You need to set content type as null
headers.set('Content-Type', null);
headers.set('Accept', "multipart/form-data");
headers.set('encType', "multipart/form-data");
let params = new HttpParams();
return this.http.post(baseUrl+"/uploadFile", formData, { headers ,params});
}
弹簧靴
@PostMapping(value = "/importStackup", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<String> importStackSet(@RequestParam("file") MultipartFile multiPart) {
//code
}
错误:
[36m.w.s.m.s.DefaultHandlerExceptionResolver[0;39m [2m:[0;39m Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported]
尝试在您的服务中将
Content-type
设置为undefined
而不是null
importFile()
方法:
headers.set('Content-Type', undefined)