FileUpload Multipart Springboot错误->所需的请求部分“文件"不存在 [英] FileUpload Multipart Springboot Error -> Required request part 'file' is not present
问题描述
我正在尝试使用Angular 4.0和SpringBoot Application上传json文件.我已经检查并尝试了Stackoverflow的其他解决方案,但是我无法弄清楚确切的问题是什么.
I am trying to upload a json file using Angular 4.0 and SpringBoot Application. I have checked and tried other solutions from Stackoverflow, but I cannot figur out what the exact problem is.
我收到400 BAD Request Error消息,并显示以下消息:所需的请求部分'file'不存在.
I receive the 400 BAD Request Error message with the message: Required request part 'file' is not present.
我的RestController看起来像这样(出于测试目的),但是不幸的是没有任何反应.
My RestController looks like this (for testing purposes), but unfortunately nothing happens.
@RestController
@RequestMapping("/api")
public class UploadRequestResource {
....
@PostMapping("/fileupload")
@Timed
public ResponseEntity<Endpoint> FileUpload(@RequestParam("file") MultipartFile file) throws URISyntaxException {
if (file.isEmpty()) {
System.out.println("File is empty"); }
System.out.println("File is not empty");
//some logic
return ResponseEntity.ok() ....
}
}
我已在我的应用程序配置文件中添加了以下内容:
I have added the following in my applicatoin configuration file:
spring:
http:
multipart:
max-file-size: 5MB
max-request-size: 20MB
我的HTML文件如下:
My HTML File looks like this:
<form name="editForm" role="form" novalidate (ngSubmit)="save()" #editForm="ngForm">
...
<input type="radio" [(ngModel)]="form.uploadType" name="uploadType" value="file"> <label for="url">File</label><br>
<input type="file" name="file" placeholder="Upload file..." (change)="onFileChange($event)" (focus)="onFileFocus()"/>
</div>
</div>
Angular ts文件如下所示:
The Angular ts file looks like this:
fileUpload(data): Observable<Endpoint> {
let headers = new Headers({ 'Content-Type': 'multipart/form-data' });
let options = new RequestOptions({ headers: headers });
return this.http.post('/api/fileupload', data , options).map((res: Response) => {
const jsonResponse = res.json();
return this.convertItemFromServer(jsonResponse);
});
}
有人知道我应该如何解决此错误?我会很感激任何帮助.谢谢
Does anyone has any idea how I should solve this error? I would be so gratful for any help. thanks
推荐答案
所以我找到了解决问题的方法.取而代之的是使用Content-Type:"multipart/form-data"我使用了Formdata(请参见下文).
So I found a solution to my problem. Instead using Content-Type: "multipart/form-data" I used Formdata (see below).
const formData = new FormData();
formData.append('file', data, data.name);
return this.http.post('/api/fileupload', formData).map((res: Response) => {
const jsonResponse = res.json();
return this.convertItemFromServer(jsonResponse);
现在可以正常工作了.
Now it works fine.
这篇关于FileUpload Multipart Springboot错误->所需的请求部分“文件"不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!