我想做的事情:当用户上传一个*.json
文件时(实际上是三个,但是省略了另外两个来首先测试一个文件的情况),控制器解析JSON和更改数据库中的值。该文件将不会存储到任何地方,而只会在读取后丢弃。
控制器方法:
@RequestMapping(value = "/update/post", method = RequestMethod.POST, consumes = "multipart/form-data")
public String updateP
(
Model model,
@RequestParam(value = "dancer_info", required = false) MultipartFile dancerInfo,
// if required set to true, it says "Required request part 'dancer_info' is not present".
HttpServletRequest request
)
{
if (dancerInfo == null)
{
model.addAttribute("dancer", "Null");
}
else
{
String jsonDancerInfo = dancerInfo.toString();
model.addAttribute("dancer", jsonDancerInfo);
}
return "update_complete";
}
update.html
中的表单(使用Bootstrap 4):
<form th:action="@{/update/post}" method="post" enctype="multipart/form-data">
<div class="input-group mb-3">
<div class="custom-file">
<input type="file" class="custom-file-input" id="dancer_info" name="dancer_info">
<label class="custom-file-label" for="dancer_info">dancer_info.json</label>
</div>
</div>
<div class="input-group mb-3 justify-content-center align-items-center">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>
</form>
MultipartResolver
bean:
@Bean
public MultipartResolver multipartResolver()
{
CommonsMultipartResolver mr = new CommonsMultipartResolver();
mr.setMaxInMemorySize(102400);
mr.setMaxUploadSize(102400);
return mr;
}
模板update_complete.html
:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>dancer <span th:text="${dancer}"></span></p>
</body>
</html>
结果: dancer Null
dancer dancer_info.json
或MultipartFile.toString()
的东西我之前尝试过的内容:
StandardServletMultipartResolver
代替CommonsMultipartResolver
:我找不到与之等效的setMaxUploadSize()
,因此无法应用。@RequestBody
代替@RequestParam
:结果相同。dancer_info
重命名为file
:结果相同。我的案件缺少什么?
name="dancer_info"
标记中添加了<input>
,但结果相同。