728x90
반응형
스프링MultipartFile멀티(다중)파일 업로드[@ModelAttribute이용,Spring Framework3.X MVC multiple file upload]

1. fileupload 라는 spring mvc 프로젝트 생성
 
[전체구조]
 


 
[pom.xml]
 
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>onj.springframework.samples</groupId>
 <artifactId>springmvc</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <properties>
  <!-- Generic properties -->
  <java.version>1.7</java.version>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <!-- Spring -->
  <spring-framework.version>3.2.3.RELEASE</spring-framework.version>
  <!-- Logging -->
  <logback.version>1.0.13</logback.version>
  <slf4j.version>1.7.5</slf4j.version>
  <!-- Test -->
  <junit.version>4.11</junit.version>
 </properties>
 <dependencies>
  <!-- Spring and Transactions -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring-framework.version}</version>
  </dependency>
<!-- Servlet -->
 <dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>  
  <!-- Apache Commons file upload -->
  <dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.2.2</version>
  </dependency>
  <!-- Apache Commons IO -->
  <dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-io</artifactId>
   <version>1.3.2</version>
  </dependency>
  <!-- JSTL for c: tag -->
  <dependency>
   <groupId>jstl</groupId>
   <artifactId>jstl</artifactId>
   <version>1.2</version>
  </dependency>
 </dependencies>
</project>

2. 모델 작성
 
fileupload.jsp에서 넘기는 폼 데이터를 @ModelAttribute로 받기 위한 객체
 
[FileForm.java]
 
package onj.spring.fileupload.model;

import java.util.List;
import org.springframework.web.multipart.MultipartFile;


public class FileForm {
private List<MultipartFile> files;
private String upDir;

public List<MultipartFile> getFiles() {
return files;
}

public String getUpDir() {
return upDir;
}

public void setUpDir(String upDir) {
this.upDir = upDir;
}

public void setFiles(List<MultipartFile> files) {
this.files = files;
}
}


3. 컨트롤러 작성
 
[OnjController.java]
 
package onj.spring.fileupload.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import onj.spring.fileupload.model.FileForm;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class OnjController {

@RequestMapping(value = "/view", method = RequestMethod.GET)
public String displayForm() {
return "fileupload";
}

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@ModelAttribute("uploadForm") FileForm uploadForm,
Model map) throws Exception {
List<MultipartFile> files = uploadForm.getFiles();

// success.jsp 로 보낼 파일 이름 저장
List<String> fileNames = new ArrayList<String>();

if (null != files && files.size() > 0) {
for (MultipartFile multipartFile : files) {
String fileName = multipartFile.getOriginalFilename();

String path = uploadForm.getUpDir() + fileName;

File f = new File(path);

multipartFile.transferTo(f);

fileNames.add(fileName);

}
}

map.addAttribute("files", fileNames);
return "success";
}
}




4.  /src/main/webapp/jsp/fileupload.jsp
 
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<html>
<head>
    <title>OnJ, OracleJavaCommunity</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
<!-- jquery로 파일 첨부 추가 -->
$(document).ready(function() {
    //add more file components if Add is clicked
    $('#addFile').click(function() {
        var fileIndex = $('#fileview tr').children().length;      
        $('#fileview').append(
                '<tr><td>'+
                '   <input type="file" name="files['+ fileIndex +']" />'+
                '</td></tr>');
    });     
});
</script>
</head>
<body>
<h3>Spring WEB MVC MuliFile Upload(oraclejava community)</h3>
 
<form:form method="post" action="save.html"
      modelAttribute="uploadForm" enctype="multipart/form-data">
 
    Upload Directory : <input type="text" name="upDir" value="c:/java/project/upload/"/><br><br>
    <input id="addFile" type="button" value="File Add" />    
    <table id="fileview">
        <tr>
            <td><input name="files[0]" type="file" /></td>
        </tr>        
    </table>
    <br/><input type="submit" value="Upload" />
</form:form>
</body>
</html>

5. /src/main/webapp/jsp/success.jsp
 
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>Spring MVC Multiple File Upload</title>
</head>
<body>
    <p>upload ok!!</p>
    <ol>
    <!--  아래 files는 컨트롤러에서 직접 넘겨준 모델명 -->
        <c:forEach var="file" items="${files}">
            <li>${file}</li>
        </c:forEach>
        <!-- 컨트롤러에서 @ModelAttribute로 선언된 객체는 자동으로 view로 전달  -->
        <br><br>Uload Path : ${uploadForm.upDir}
    </ol>
</body>
</html>



6. /WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 id="WebApp_ID" version="2.5">
 <!-- 디스패처 서블릿 정의 설정 -->
 <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>*.html</url-pattern>
 </servlet-mapping>
</web-app>
 
7. /WEB-INF/springmvc-servlet.xml
 
 <context:annotation-config />
 <context:component-scan base-package="onj.spring.fileupload.controller" />
 <bean id="multipartResolver"
  class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
 <bean id="jspViewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/jsp/" />
  <property name="suffix" value=".jsp" />
 </bean>
</beans>

8. 실행(context명/view.html)
 
실행하면 파일은 c:\java\project\upload 폴더에 생성된다.
728x90
반응형
블로그 이미지

nineDeveloper

안녕하세요 현직 개발자 입니다 ~ 빠르게 변화하는 세상에 뒤쳐지지 않도록 우리모두 열심히 공부합시다 ~! 개발공부는 넘나 재미있는 것~!

,