Spring MVC File Upload Esempio

Introduzione

In questo tutorial, si mostra come gestire l’upload di più file in una Spring MVC web application

Creazione Progetto

Dal meù File/New/Other  cliccare su “Maven Project


Checkare “Create a simple project (skip archetype selection)

Inserire i seguenti valori:
Group ID: iljavarolo
Artifact ID: springuploadfile
Packaging: war

Cliccare su “Finish

Il progetto creato dovrebbe avere una struttura del genere:

Se non esiste la cartella WEB-INF crearla:

Configurazione Maven

file  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>iljavarolo</groupId>
  <artifactId>springuploadfile</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>springuploadfile</name>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
 
 
        <!-- Servlet API -->
        <!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
 
        <!-- Jstl for jsp page -->
        <!-- http://mvnrepository.com/artifact/javax.servlet/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
 
 
        <!-- JSP API -->
        <!-- http://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>
 
 
        <!-- Spring dependencies -->
        <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
 
        <!-- http://mvnrepository.com/artifact/org.springframework/spring-web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
 
        <!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
 
 
        <!-- Apache Commons FileUpload -->
        <!-- http://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
 
        <!-- Apache Commons IO -->
        <!-- http://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
 
 
    </dependencies>
 
 
 
    <build>
        <finalName>SpringMVCFileUpload</finalName>
        <plugins>
 
            <!-- Config: Maven Tomcat Plugin -->
            <!-- http://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat7-maven-plugin -->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>

            </plugin>
        </plugins>
    </build>
</project>

Configurazione Spring

file  web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   version="3.0">
 
   <display-name>Archetype Created Web Application</display-name>
   <servlet>
       <servlet-name>spring-mvc</servlet-name>
       <servlet-class>
           org.springframework.web.servlet.DispatcherServlet
       </servlet-class>
       <load-on-startup>1</load-on-startup>
   </servlet>
 
   <servlet-mapping>
       <servlet-name>spring-mvc</servlet-name>
       <url-pattern>/</url-pattern>
   </servlet-mapping>
 
   <!-- Other XML Configuration -->
   <!-- Load by Spring ContextLoaderListener -->
   <context-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>
          /WEB-INF/root-context.xml
        </param-value>        
   </context-param>
 
 
   <!-- Spring ContextLoaderListener -->
   <listener>
       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>
 
</web-app>

Da notare che:

  • Il listener ContextLoaderListener di Spring legge il file di configurazione dal paramento contextConfigLocation  del web.xml, che in questo caso vale  /WEB-INF/root-context.xml
  • La DispatcherServlet di Spring leggerà il suo file di configurazione in base al principio {servlet-name} ==> /WEB-INF/{servlet-name}-servlet.xml, quindi in questo caso la servlet name vale “spring-mvc”   e il file avrà il nome di “spring-mvc-servlet.xml”       

file root-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">
 
   <!-- Empty -->
 
</beans>

file spring-mvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-4.1.xsd  
     http://www.springframework.org/schema/mvc
     http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
 
   <!-- Package Scan -->
   <context:component-scan base-package="com.iljavarolo.springmvcfileupload" />
    
   <!-- Enables the Spring MVC Annotation Configuration -->
   <context:annotation-config />
 
   <bean
       class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 
       <property name="prefix">
           <value>/WEB-INF/pages/</value>
       </property>
 
       <property name="suffix">
           <value>.jsp</value>
       </property>
 
   </bean>
    
    
   <bean id="multipartResolver"
       class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
 
        <!-- Maximum file size: 1MB -->
        <!-- 1MB = 125000 Byte -->
       <property name="maxUploadSize" value="125000" />
 
   </bean>
 
</beans>

Creazione Classi Java

file MyFileUploadController.java

package com.iljavarolo;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
 
@Controller
public class MyFileUploadController {
 
    // Upload One File.
    @RequestMapping(value = "/uploadOneFile")
    public String uploadOneFileHandler() {
        // Forward to "/WEB-INF/pages/uploadOneFile.jsp".
        return "uploadOneFile";
    }
 
    // Upload Multi File.
    @RequestMapping(value = "/uploadMultiFile")
    public String uploadMultiFileHandler() {
        // Forward to "/WEB-INF/pages/uploadMultiFile.jsp".
        return "uploadMultiFile";
    }
 
    // uploadOneFile.jsp, uploadMultiFile.jsp submit to.
    @RequestMapping(value = "/doUpload", method = RequestMethod.POST)
    public String uploadFileHandler(HttpServletRequest request, Model model,
            @RequestParam("file") MultipartFile[] files) {
 
        // Root Directory.
        String uploadRootPath = request.getServletContext().getRealPath(
                "upload");
        System.out.println("uploadRootPath=" + uploadRootPath);
 
        File uploadRootDir = new File(uploadRootPath);
        //
        // Create directory if it not exists.
        if (!uploadRootDir.exists()) {
            uploadRootDir.mkdirs();
        }
        //
        List<File> uploadedFiles = new ArrayList<File>();
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
 
            // Client File Name
            String name = file.getOriginalFilename();
            System.out.println("Client File Name = " + name);
 
            if (name != null && name.length() > 0) {
                try {
                    byte[] bytes = file.getBytes();
 
                    // Create the file on server
                    File serverFile = new File(uploadRootDir.getAbsolutePath()
                            + File.separator + name);
 
                    // Stream to write data to file in server.
                    BufferedOutputStream stream = new BufferedOutputStream(
                            new FileOutputStream(serverFile));
                    stream.write(bytes);
                    stream.close();
                    //
                    uploadedFiles.add(serverFile);
                    System.out.println("Write file: " + serverFile);
                } catch (Exception e) {
                    System.out.println("Error Write file: " + name);
                }
            }
        }
        model.addAttribute("uploadedFiles", uploadedFiles);
        return "uploadResult";
    }
 
}

Creazione Viste

file uploadOneFile.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload One File</title>
</head>
<body>
 
    <h3>Upload One File:</h3>
 
    <form method="POST" action="doUpload" enctype="multipart/form-data">
        File to upload: <input type="file" name="file"><br />       
        <input type="submit" value="Upload">
    </form>
     
</body>
 
</html>

file uploadMultiFile.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload Multi File</title>
</head>
<body>
 
   <h3>Upload Multiple File:</h3>
    
    <form method="POST" action="doUpload" enctype="multipart/form-data">
 
        File to upload (1): <input type="file" name="file"><br />      
        File to upload (2): <input type="file" name="file"><br />  
        File to upload (3): <input type="file" name="file"><br />  
        File to upload (4): <input type="file" name="file"><br />  
        File to upload (5): <input type="file" name="file"><br />   
         
        <input type="submit" value="Upload">
 
    </form>
     
     
</body>
</html>

file uploadResult.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
     
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload Result</title>
</head>
<body>
   <h3>Uploaded Files:</h3>
  
    <c:forEach items="${uploadedFiles}" var="file">
           - ${file} <br>
    </c:forEach>
 
</body>
</html>

Build  Applicazione

Buildare l’intero progetto, cliccando su run As–>Maven Install

Dal menù “Run Configuration” settare la seguente configurazione per l’avvio:

inserire i seguenti valori:
Name: Run SpringMVCFileUpload
Base directory: ${workspace_loc:/SpringMVCFileUpload}
Goals: tomcat7:run

Buildare l’intero progetto cliccando su “Run“:

Avvio Applicazione

Nel browser digitare i seguenti indirizzi:

  • http://localhost:8080/SpringMVCFileUpload/pages/uploadOneFile.jsp

Scegliere il file, tramite il tasto “Choose File“, e premere “Upload

  • http://localhost:8080/SpringMVCFileUpload/pages/uploadMultiFile.jsp

Scegliere i files, tramite il tasto “Choose File“, e premere “Upload

Download sorgenti intero progetto

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *