我正在尝试创建文件上传实用程序,当我点击submit
按钮时出现以下错误。它开始上传,然后突然出现此错误:
There was an unexpected error (type=Bad Request, status=400).
Required request part 'file' is not present
我没有堆栈跟踪,这些都显示在我的窗口或控制台中。我已经找到了其他解决方案,他们最终都忘了在他们的html文件中包含name="file"
。我已经确定它已包含在内并仍然出现错误。
以下是我的上传表单:
<div id="custom-search-input">
<label>Select a file to upload</label>
<form action="/upload" enctype="multipart/form-data" method = "post">
<div class="input-group col-md-12">
<input type="file" name="file" class="search-query form-control"/>
<span class="input-group-btn">
<button type="submit" class="btn btn-success">Upload </button>
</span>
</div>
</form>
</div>
这是我上传的控制器方法:
@Value("${upload.path}")
private String path;
@RequestMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file, Model model, HttpSession session) throws IOException {
if(!file.isEmpty()) {
//Get the user
User user = (User) session.getAttribute("user");
//Get the file name
String fileName = file.getOriginalFilename();
InputStream is = file.getInputStream();
//Store the uploaded file into the users directory in the system path
Files.copy(is, Paths.get(path + user.getNetworkId() + "\\" + fileName),StandardCopyOption.REPLACE_EXISTING);
return "redirect:/success.html";
} else {
return "redirect:/index.html";
}
}
还要注意我为我的上传方法尝试了这个:
public String upload(@RequestParam(name="file",required=true) MultipartFile file, Model model, HttpSession session)
作为参考,this是我推荐的内容。
根据下面的一些答案,我尝试单独创建PostMapping
方法,以及@RequestMapping(value="/upload", method = RequestMethod.POST)
我仍然收到错误。
答案 0 :(得分:1)
一段时间后,我能够解决此问题:在我的application.properties文件中,添加了以下内容:
spring.servlet.multipart.max-file-size=128MB
spring.servlet.multipart.max-request-size=128MB
spring.http.multipart.enabled=true
upload.path=/export/home/
答案 1 :(得分:0)
您需要处理表格@GetMapping
来处理
@RequestMapping
我认为默认得到。因此,当您“获取”页面时,它会尝试按下您期望文件的方法。 take a look at my example
答案 2 :(得分:0)
您的观看代码中的<form>
方法为POST
<form action="/upload" enctype="multipart/form-data" method = "post">
在控制器中将@RequestMapping("/upload")
更改为
@RequestMapping(value = "/upload", method = RequestMethod.POST)
答案 3 :(得分:0)
我建议使用@RequestPart。如果您要使用from-data上载文件,请尝试如下重写代码:
@PostMapping("/upload")
public ResponseEntity<CustomResponse> uploadFile(@RequestPart(value = "file",required = true) MultipartFile file,
@RequestPart(value = "metadata",required = true) Metadata metadata,
HttpServletResponse response)