티스토리 뷰

반응형

 이런 간단한 문제로 며칠을 헤맸다는 사실이 매우 창피하지만, 같은 실수를 반복하지 않기 위해 삽질로그를 남긴다. Spring boot & thymeleaf로 다중 파일업로드를 처리하려면, 몇가지 간단한 절차만 수행하면된다. 


1. .properties 설정

2. html 개발

3. java 개발





1. .properties 설정

 설정을 하지 않아도 상관 없지만, application.properties 파일을 열어 아래와 같이 추가해주면 좋다.


multipart.maxFileSize=5MB 

multipart.maxRequestSize=5MB


최대 허용 파일 크기를 5MB로 넉넉하게 잡은 것이다. Default값은 1MB이다.




2. html 개발 (화면 개발)

 <input> 태그를 이용하여 개발하면 된다. 다중 파일업로드를 하므로, "multiple"을 이용하는데, 아래와 같이 개발하면 된다.


<form th:action="@{/api/image/upload}" method="post" 
    enctype="multipart/form-data" class="col m8 s12 offset-m2">
    
    <div class="input-field col s6">
        <input multiple="multiple" type="file" name="files"/>
    </div>
    
    <div class="input-field col s6">
        <button class="btn indigo waves-effect waves-light" 
            type="submit" name="save">
            
            Submit<i class="mdi-content-send right"></i>
        </button>
    </div>
</form>


 나는 input태그의 name부분에서 해맸는데, 일반적으로 Spring과 JSP를 기반으로 하여 개발할 때처럼 name을 배열로 선언(name="files[]")해야만 하는 것인줄 알았다. 왜냐하면 여러건을 보낼꺼니까.. (결국은 그게 아니었지만...)


 한편, 예제에서는 thymeleaf를 사용했고, 서버측에서 RestController로 개발했다는 것도 유추할 수 있는데, 이에 대한 가이드는 따로 하지 않겠다.





3. .java 개발

 이제 마지막으로 input태그를 이용해 전송한 파일을 어떻게 처리할 것인지에 대해 구현한다. 아래의 예제를 참고하자. 


@RestController
@RequestMapping(value = "/api/image")
public class ImageApiController {
 
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public List<MultipartFile> upload(MultipartFile[] files) {
 
        // PROCESS...
 
    }
}


생각보다 간단하게 구현된다. HttpServletRequest를 사용하지 않고도, 배열(Array)형태로 file을 받아볼 수 있다. HttpServletRequest의 getFiles() 메소드를 사용하면 List<MultipartFile> 형태로 파일 목록을 받아볼 수 있지만, Java8의 Arrays, Filter 등을 사용하면 배열 형태를 간단하게 List로 변환할 수 있다. (관련하여 추후에 포스팅)





-끝-




반응형
최근에 올라온 글
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함
Total
Today
Yesterday