Spring
Spring - 파일 업로드 하기
블린더르
2019. 2. 23. 23:08
스프링에서 파일 업로드 하기
pom.xml
먼저 pom.xml 에 dependency 를 추가합니다.
commons-io 와 commons-fileupload 를 추가합니다.
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!-- 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.xml 에 파일 업로드 객체를 설정합니다.
<!-- 파일 업로드 객체 설정 -->
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="10485760"/><!-- 10MB -->
</beans:bean>
id 값을 쓰실 때 대 소문자 구분을 꼭 해주세요 p가 소문자입니다.
maxUploadSize의 크기는 마음대로 넣어주어도 되지만 꼭 계산된 값으로 넣어야 합니다.
10 * 1024 * 1024 -> 10485760
form
파일 업로드를 테스트 하기 위해 간단한 jsp 파일을 만듭니다.
<form action="${pageContext.request.contextPath }/file/upload.do" method="post" enctype="multipart/form-data">
<label><input type="file" name="upload" /></label>
<label><input type="file" name="upload" /></label>
<input type="submit" value="업로드" />
</form>
form 태그의 enctype 속성은 multipart/form-data 로 넣어줍니다.
하나의 input 태그로 여러 개의 파일을 전송하려면 multiple 속성을 넣어줍니다.
<input type="file" name="upload" multiple />
Controller
폼에서 넘긴 값을 받아오는 간단한 컨트롤러를 만듭니다.
@Controller
public class FileController {
@RequestMapping("/file/upload.do")
public String uploadFile(MultipartFile[] upload, HttpServletRequest request) {
//파일이 업로드 될 경로 설정
String saveDir = request.getSession().getServletContext().getRealPath("/resources/upload/file");
//위에서 설정한 경로의 폴더가 없을 경우 생성
File dir = new File(saveDir);
if(!dir.exists()) {
dir.mkdirs();
}
// 파일 업로드
for(MultipartFile f : upload) {
if(!f.isEmpty()) {
// 기존 파일 이름을 받고 확장자 저장
String orifileName = f.getOriginalFilename();
String ext = orifileName.substring(orifileName.lastIndexOf("."));
// 이름 값 변경을 위한 설정
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmssSSS");
int rand = (int)(Math.random()*1000);
// 파일 이름 변경
String reName = sdf.format(System.currentTimeMillis()) + "_" + rand + ext;
// 파일 저장
try {
f.transferTo(new File(saveDir + "/" + reName));
}catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
}
}
return "uploadEnd";
}
}
매개 변수의 MultipartFile 배열이 폼에서 넘어오는 파일들의 배열이다.
파일을 하나씩 이름이 중복되지 않도록 바꿔서 저장한다.
테스트 하기
이미지 파일 2개를 선택했습니다.
업로드 버튼을 누르면
업로드 완료 창이 뜹니다.
폴더에 파일이 잘 들어가는지 확인합니다.
새로고침을 누르니 방금 업로드한 파일이 이름이 바뀌어서 저장된 것을 확인할 수 있습니다.
반응형