英文:
Spring Boot - Angular: Current request is not a multipart request
问题
以下是您要翻译的内容:
"I'm trying to upload a file from Angular front-end to Spring Boot back-end.
HTML:
<button type="button" (click)="fileInput.click()">
<span>Upload</span>
<input #fileInput type="file" (change)="onFileChange($event)" style="display: none" />
</button>
<button class="button" (click)="uploadDocumento()">Upload</button>
TS:
onFileChange(event: any) {
this.file = event.target.files[0];
}
uploadDocumento() {
if (this file) {
this.baseService.uploadfile(this.file, this.url).subscribe(resp => {});
}
}
public uploadfile(file: File, url: string) {
let formParams = new FormData();
formParams.append('file', file);
return this.httpClient.post(url, formParams);
}
Spring Boot:
@PostMapping("/uploadFile")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
LOGGER.info(file);
return null;
}
I get the error: "org.springframework.web.multipart.MultipartException: Current request is not a multipart request."
What am I doing wrong? Thanks in advance"
注意:原始内容中的HTML、TS和Spring Boot代码已被保留,但文本中的HTML和TS代码已翻译成普通文本格式,以方便阅读。
英文:
I'm trying to upload a file from Angular front-end to Spring Boot back-end.
HTML:
<button type="button" (click)="fileInput.click()">
<span>Upload</span>
<input #fileInput type="file" (change)="onFileChange($event)" style="display: none" />
</button>
<button class="button" (click)="uploadDocumento()">Upload</button>
TS:
onFileChange(event: any) {
this.file = event.target.files[0];
}
uploadDocumento() {
if (this.file) {
this.baseService.uploadfile(this.file, this.url).subscribe(resp => {});
}
}
public uploadfile(file: File, url: string) {
let formParams = new FormData();
formParams.append('file', file);
return this.httpClient.post(url, formParams);
}
Spring Boot:
@PostMapping("/uploadFile")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
LOGGER.info(file);
return null;
}
I get the error: "org.springframework.web.multipart.MultipartException: Current request is not a multipart request"
What am I doing wrong? Thanks in advance
答案1
得分: 1
尝试在前端再次操作,您需要使用具有以下标头的请求传递下去:
'Content-Type': 'multipart/form-data'
英文:
Try again on frontend, you need transfer request down with header has more:
'Content-Type': 'multipart/form-data'
答案2
得分: 0
你可以尝试通过以下方式在后端替换 API 的标题:
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
英文:
you can try to replace the header of api in backend by
this line.
@RequestMapping(value = "/uploadFile",
method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
答案3
得分: 0
已解决。我的拦截器会将" 'Content-Type': 'application/json' "添加到任何HTTP请求中。
英文:
Resolved. My interceptor add "'Content-Type': 'application/json'" to any http request.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论