잡동사니

반응형

질문

여러 파일을 바이트 배열로 객체에 바인딩하려고하지만 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>

testObject는 다음과 같습니다.

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";
}

답변1

수행해야 할 두 가지 변경 사항이 있습니다.

  1. 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속성은 th : field이름을 사용하여 Thmeleaf에 의해 생성되기 때문에 제공 할 필요가 없습니다.

  1. TestObjectclass를 업데이트하여 privatekeypublickey유형을 org.springframework.web.multipart.MultipartFile <유형으로 변경합니다. / code> 이렇게하면 원본 파일 이름, 콘텐츠 유형과 같은 파일의 다른 메타 데이터뿐만 아니라 파일 바이트를 얻을 수 있습니다.


 

 

 

 

출처 : https://stackoverflow.com/questions/59125303/thymeleaf-bind-file-to-object

반응형

이 글을 공유합시다

facebook twitter googleplus kakaoTalk kakaostory naver band