file upload 구현하기
- commons-fileupload : 파일 업로드 라이브러리
- commons-io : MultipartFile 사용 라이브러리
업로드 규칙 1: POST 방식으로 보낸다.
업로드 규칙 2: enctype 설정.
업로드 규칙 3. 업로드할 크기를 지정해 준다.
<!-- fileupload 관련 -->
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
<!-- /photo 라는 요청이 들어오면 C:/upload 로 연결해라 -->
<Context docBase="C:/upload" path="/photo/"/>
<!-- upload 규칙 3. 업로드할 크기를 지정해 준다. -->
<!-- encodin 설정 -->
<!-- 업로드 크기 설정 (MaxFileSize)-->
<!-- 버퍼에 저장할 용량 (FilesizeTreadhold)-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="50000000"/>
<property name="maxInMemorySize" value="50000000"/>
</bean>
public void upload(MultipartFile uploadFile) {
// 1. 파일명 추출
String fileName = uploadFile.getOriginalFilename();
// 2. 파일명 변경 -> 중복되지 않는 이름으로 변경(현재시간을 밀리초로 환산한 이름)
String ext = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
String newFileName = System.currentTimeMillis()+ext; // 123456421342.jpg
System.out.println("변경된 파일명 : "+newFileName);
// 3. 파일 저장(java.nio)
try {
// 3-1. 객체로 부터 바이트 추출
byte[] arr = uploadFile.getBytes();
// 3-2. 저장할 경로와 파일명 지정
Path path = Paths.get(root+"upload/"+newFileName);
// 3-3. 파일 저장
Files.write(path, arr);
} catch (Exception e) {
e.printStackTrace();
}
}
public void multiUpload(MultipartFile[] files) {
// 1. 배열 안의 파일객체를 하나씩 꺼내서
for (MultipartFile file : files) {
try {
// 2. upload() 에서 했던 내용을 실행 해 준다.
upload(file); // 파일용량이 적으면 1밀리세컨드 안에 여러 파일을 업로드 하여 이름이 같아질 수 있다.
Thread.sleep(1); // 강제로 1밀리 세컨드씩 지연을 시킨다.
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
<form action="multiUpload" method="post" enctype="multipart/form-data">
<input type="file" name="files" multiple="multiple"/>
<input type="submit" value="전송"/>
</form>