首页 > 解决方案 > 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";
}

标签: javaspringthymeleaf

解决方案


您需要进行两项更改:

  1. 添加enctypeform 元素并更新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名称创建。

  1. 更新您的TestObject类以更改类型privatekeypublickey类型,org.springframework.web.multipart.MultipartFile 这样您将获得文件字节以及文件的其他元数据,如原始文件名、内容类型。

推荐阅读