Spring 2.5에서 파일을 업로드하려면 다음과 같은 절차를 따라서 하면 된다.
참고: Spring 2.5의 기본 라이브러리 설정방법은 [Spring IDE설정]을 참고하세요.
1. 라이브러리 포함: Apache File Upload를 WEB-INF/lib안에 import한다.
2. web.xml파일 설정
- web.xml의 인코딩필터 설정부분
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>EUC-KR</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2. 설정파일(dispatcher-servlet.xml)에 multipartResolver 및 폼 콘트롤러 설정
- 폼 콘트롤러 설정: AbstractCommandController나 SimpleFormController를 상속하면 된다.
- Command Class를 설정한다.
- 반드시 multipartResolver 라는 이름의 업로드 빈을 설정해야 한다.
- dispatcher-servlet.xml 파일의 관련 빈 설정부분
<bean name="/upload/upload.htm"
class="upload.UploadFormController"
p:commandClass="upload.UploadCommand"
p:commandName="uploadCommand"
p:successView="upload/uploadSuccess"
p:formView="upload/uploadForm" />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
3. Command 클래스 작성
- 폼 필드의 값과 업로드된 파일의 정보를 저장할 수 있는 속성이 선언되어야 한다.
- 업로드된 파일정보는 org.springframework.web.multipart.MultipartFile 클래스에 저장된다.
- 그러므로 반드시 MultipartFile형의 속성을 선언해 주어야만 업로드된 파일의 정보가 저장된다.
- upload.UploadCommand.java
package upload;
import org.springframework.web.multipart.MultipartFile;
public class UploadCommand {
private String author;
private String description;
private MultipartFile file1; /* 업로드된 파일의 정보가 저장될 클래스 */
private MultipartFile file2;
public UploadCommand() {}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public MultipartFile getFile1() {
return file1;
}
public void setFile1(MultipartFile file1) {
this.file1 = file1;
}
public MultipartFile getFile2() {
return file2;
}
public void setFile2(MultipartFile file2) {
this.file2 = file2;
}
}
4. FormController클래스 작성
- 여기서는 SimpleFormController를 상속하여 작성하려고 한다
- onSubmit()를 오버라이드 하여 커맨드객체에 저장된 파일정보를 이용하여 원하는 곳으로 파일을 옮겨 놓는다.
- 예제에서는 D:/upload/fileName 경로에 저장하는 예를 들었다.
- Validator를 구현하여 폼을 검증하게 할 수도 있다 (이 경우, 폼검증에 통과하지 못하면 다시 formView로 간다)
- 업로드에 성공하면 등록된 successView를 출력하도록 한다
- successView에서 커맨드객체를 사용할 수 있도록 ModelAndView.addAllObjects(errors.getModel())을 사용한다
- upload.UploadFormController.java
package upload;
import java.io.File;
import javax.servlet.http.*;
import org.springframework.validation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.*;
import org.springframework.web.servlet.mvc.*;
public class UploadFormController extends SimpleFormController {
@Override
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
UploadCommand uc = (UploadCommand) command;
String author = uc.getAuthor();
String description = uc.getDescription();
System.out.println("author:"+author);
System.out.println("desc:"+description);
MultipartFile file1 = uc.getFile1();
MultipartFile file2 = uc.getFile2();
String file1Name = file1.getOriginalFilename();
String file2Name = file2.getOriginalFilename();
System.out.println("fileName:"+file1Name+"/"+file2Name);
String savePath = "d:/upload/";
file1.transferTo(new File(savePath+file1Name));
file2.transferTo(new File(savePath+file2Name));
ModelAndView mav = new ModelAndView();
mav.setViewName(getSuccessView());
mav.addAllObjects(errors.getModel());
return mav;
}
}
5. formView작성(uploadForm.jsp)
- 일반 폼 필드(작성자, 파일설명 등)를 이용하여 파일이 아닌 폼 데이터도 전송할 수 있다.
- input type="file" name="file1" 과 같은 형식으로 파일을 업로드 할 수 있는 인터페이스를 준비한다.
- /upload/uploadForm.jsp
pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Spring 2.5 에서 파일 업로드</title>
</head>
<body><center><br></br>
다음 양식을 작성한 후에 [업로드]버튼을 눌러 주세요
<hr width="40%">
<form action="upload.htm" method="post" enctype="multipart/form-data">
<table>
<tr><th>작성자</th>
<td><input type="text" name="author" value="홍길동"></td></tr>
<tr><th>설 명</th>
<td><input type="text" name="description" value="파일업로드 테스트"></td></tr>
<tr><th>파일 1</th>
<td><input type="file" name="file1"></td></tr>
<tr><th>파일 2</th>
<td><input type="file" name="file2"></td></tr>
<tr><td colspan="2" align="left"><input type="submit" value="업로드"></td></tr>
</table>
</form>
</center>
</body>
</html>
6. successView (uploadSuccess.jsp)작성
- 콘트롤러에서 커맨드 객체를 전달해 주면 이 뷰에서도 커맨드객체의 데이터를 출력할 수 있다.
- 커맨드 객체를 사용하려면 설정파일에 등록한 커맨드객체의 이름속성 값을 사용하면 된다.
- 예를 들어, 커맨드클래스의 이름이 uploadCommand라면 ${uploadCommand.author} 과 같이 하면 된다.
- /upload/uploadSuccess.jsp
pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Spring 2.5 에서 파일 업로드</title>
</head>
<body><center><br></br>
파일 업로드 결과는 다음과 같습니다.
<hr width="40%">
<table>
<tr><th>작성자</th>
<td>${uploadCommand.author}</td></tr>
<tr><th>설 명</th>
<td>${uploadCommand.description}</td></tr>
<tr><th>파일 1</th>
<td>${uploadCommand.file1.originalFilename}</td></tr>
<tr><th>파일 2</th>
<td>${uploadCommand.file2.originalFilename}</td></tr>
</table>
</center>
</body>
</html>