파일 업로드에 필요한 라이브러리들을 pom.xml에 입력합니다.
pom.xml
<!-- Apache Commons FileUpload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- Apache Commons IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
root-context.xml
<!-- MultipartResolver 설정 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000000" />
<property name="maxInMemorySize" value="100000000" />
</bean>
파일을 받을 수 있도록 해주는 MultipartResolver 빈을 주입해 줍니다. maxUploadSize 속성으로 업로드될 파일의 최대 크기를 설정할 수 있고 maxInMemorySize로 메모리에 유지되도록 허용할 수 있는 최대 용량을 설정할 수 있습니다.
파일을 전송할 jsp화면입니다.
예시
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="제출"/>
</form>
파일 전송은 post 형식으로만 전송이 되며 enctype을 multipart/form-data로 설정합니다. 그리고 file을 올릴 input 태그를 입력합니다.
스프링 시큐리티를 사용할 경우
<form:form action="/upload?${_csrf.parameterName}=${_csrf.token}" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="제출"/>
</form:form>
스프링 시큐리티를 사용하고 있는 경우에는 요청 url 다음에 "?${_csrf.parameterName}=${_csrf.token}"을 붙여주어야 해당 url로 요청할 수 있습니다.
form 태그의 요청을 받고 실행되는 컨트롤러 파일의 메서드입니다.
예시
@RequestMapping(value = "/upload" , method = RequestMethod.POST)
public String upload(MultipartHttpServletRequest mtf) throws Exception {
// 파일 태그
String fileTag = "file";
// 업로드 파일이 저장될 경로
String filePath = "C:\\temp\\";
// 파일 이름
MultipartFile file = mtf.getFile(fileTag);
String fileName = file.getOriginalFilename();
// 파일 전송
try {
file.transferTo(new File(filePath + fileName));
} catch(Exception e) {
System.out.println("업로드 오류");
}
...
}
form 태그로 전송된 파일 정보는 MultipartHttpServletRequest라는 형태로 받게 되므로 메서드 파라미터로 넣어 줍니다. 그리고 fileTag라는 변수를 만들어서 form 태그에서 입력한 name 속성의 값을 입력합니다. filePath 변수에는 업로드한 파일이 저장될 경로를 입력합니다. 그런 다음 MultipartFile 객체를 만들어 전송받은 파일 정보를 저장하고 getOriginalFilename 메서드로 파일 이름을 fileName변수에 저장합니다. 마지막으로 transforTo 메서드에 업로드 파일의 전체 경로가 입력된 file 객체를 매개변수로 전달하면 업로드가 완료됩니다.
[Spring] 스프링 이클립스와 톰캣 연동하기 (0) | 2020.09.27 |
---|---|
[Spring] 스프링 @RequestBody, @ResponseBody 사용하기 (0) | 2020.09.27 |
[Spring] 스프링 JUnit을 이용하여 코드 테스트하기 (0) | 2020.09.27 |
[Spring] 스프링 @RestController 사용하기 (0) | 2020.09.26 |
[Spring] 스프링 HttpServletRequest, @RequestParam, @ModelAttribute를 이용하여 파라미터 받기 (0) | 2020.09.26 |