Spring
[Spring] FileUpload하기(+다중파일업로드)
ssooyn_n
2022. 4. 22. 01:34
pom.xml 설정
file을 업로드 하기 위해서는 제일 먼저 pom.xml에서 commons-fileupload를 추가해주어야 합니다.
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency> <groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
servlet-context.xml 설정
servlet-context에서 multipartResolver을 추가합니다.
주의할점은 upload파일을 resources밑에 두고 싶다면 꼭 servlet-context.xml에서 mapping을 해주어야 한다는 것 입니다.
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/upload/**" location="/resources/upload/" />
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="defaultEncoding" value="UTF-8"/>
<beans:property name="maxUploadSize" value="52428800"/> <!-- 50MB 필수x -->
<beans:property name="maxInMemorySize" value="1048576"/> <!-- 1MB 필수x-->
</beans:bean>
.jsp 파일 설정
form의 enctype="multipart/form-data"로 수정합니다.
업로드한 파일 이미지는 <img src="${pageContext.request.contextPath }/resources/upload/${user.img }">로 가져옵니다.
controller 설정
public ModelAndView doRegist(User user, @RequestParam("userImg") MultipartFile file) throws Exception {
ModelAndView mav = new ModelAndView();
// 파일을 저장 할 경로
Resource res = resLoader.getResource("resources/upload");
if(file != null && file.getSize() > 0) {
// 파일의 원래이름(*.png) 가져와서 user 객체의 setter를 통해 설정
user.setImg(file.getOriginalFilename());
// 지정한 경로에 이미지 파일 저장
file.transferTo(new File(res.getFile().getCanonicalPath() + "/" + user.getImg()));
}
// 어디로 연결할지 설정
mav.setViewName("regist_result");
// 전달할 객체
mav.addObject("user", user);
return mav;
}
RequestParam은 form에서 설정해준 name값
1. 파일을 업로드할 경로를 가져오고
2. form에서 받은 Multiparfile가 null이 아니고 fil.getSize() > 0 이면
3. userDto에 저장해준 파일(이미지)의 파일명을 set한다.
4. transferTo로 파일을 파일객체의 경로로 전송한다. uploadPath + file.getOriginalFilename() 으로 이루어져있다.
출력해보면 저 경로에 파일이 저장되는 것을 알 수 있다.
spring_hw_5_2 까지가 ${pageContext.request.contextPath}