2014년 1월 16일 목요일

스프링MultipartFile멀티(다중)파일 업로드[Spring Framework3.X MVC multiple file upload] , 구로디지털 스프링교육학원강좌,스프링프레임워크 1. fileupload 라는 spring mvc 프로젝트

스프링MultipartFile멀티(다중)파일 업로드[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>
  
  <!-- 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에서 넘기는 폼 데이터를 받기 위한 객체
 
[FileForm.java]
 
package onj.spring.fileupload.model;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;

public class FileForm {
 private List<MultipartFile> files;
 public List<MultipartFile> getFiles() {
  return files;
 }
 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 = "c:/java/project/upload/" + fileName;
   
    File f = new File(path);
   
    multipartFile.transferTo(f);
      
    fileNames.add(fileName);
   }
  }
  map.addAttribute("files", fileNames);
  return "success";
 }
}

4.  /src/main/webapps/jsp/fileupload.jsp
 
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<html>
<head>
    <title>스프링 멀티 파일 업로드</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>SpringMVC Muli File Upload example(oraclejavanew.kr)</h3>

<form:form method="post" action="save.html"
      modelAttribute="uploadForm" enctype="multipart/form-data">

    <input id="addFile" type="button" value="File Add" />
    <table id="fileview">
        <tr>
            <td><input name="files[0]" type="file" /></td>
        </tr>
        <tr>
            <td><input name="files[1]" type="file" /></td>
        </tr>
    </table>
    <br/><input type="submit" value="Upload" />
</form:form>
</body>
</html>

5. /src/main/webapps/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>
        <c:forEach items="${files}" var="file">
            <li>${file}</li>
        </c:forEach>
    </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 폴더에 생성된다.



댓글 없음:

댓글 쓰기