java - thymeleaf 将文件绑定到对象
问题描述
我正在尝试将多个文件作为字节数组绑定到一个对象,但 thymeleaf 只是将文件名绑定为字节数组。如何在控制器中捕获文件?或绑定文件字节?
html:
<form th:action="@{/add}" th:object="${testObject}" method="post">
<span>add key</span>
<input class="btn btn-primary btn-sm" th:field="*{privatekey}" type="file" name="file">
<span>add key</span>
<input class="btn btn-primary btn-sm" th:field="*{publickey}" type="file" name="file">
<button type="submit">Seve</button>
像测试对象:
public class TestObject {
...
@Column(name = "privatekey")
private byte[] privatekey;
@Column(name = "publickey")
private byte[] publickey;
}
控制器:
@PostMapping("/add")
public String singleFileUpload(@ModelAttribute("testObject") TestObject testObject,
RedirectAttributes redirectAttributes,
Principal principal) {
testObjectService.save(testObject);
return "redirect:test/page";
}
解决方案
您需要进行两项更改:
- 添加
enctype
到form
元素并更新form
如下所示:
<form th:action="@{/handle-file-upload}" th:object="${fileObj}" method="post"
enctype="multipart/form-data">
<span>add key</span>
<input class="btn btn-primary btn-sm" th:field="*{file1}" type="file">
<span>add key</span>
<input class="btn btn-primary btn-sm" th:field="*{file2}" type="file">
<button type="submit">Save</button>
</form>
使用th:field
时不需要提供name
属性,因为它将由 Thmeleaf 使用th:field
名称创建。
- 更新您的
TestObject
类以更改类型privatekey
和publickey
类型,org.springframework.web.multipart.MultipartFile
这样您将获得文件字节以及文件的其他元数据,如原始文件名、内容类型。
推荐阅读
- c - 为什么子进程运行代码意味着父进程
- python - 有没有办法从表格的两列生成 matplotlib 图?
- c# - 在 Visual Studio C# 中发出 Ping 请求
- javascript - 将嵌套的excel数据显示为json中的一个数据
- javascript - 如何向下滚动并在同一页面上显示部分?
- reactjs - 为什么在 React 中,render() 方法与“this”关键字配合得很好
- java - gradle如何将另一个子项目的代码和资源添加到子项目中
- sql - 使用和不使用 TIMEZONE 存储 DATETIME
- sql - SQL 拓扑排序
- c# - ASP.NET 网络服务安全?