Spring MVC File Upload Tutorial

Source: Internet
Author: User
Tags create directory

1-Introduction This tutorial article is based on Spring MVC to implement the file upload function, here is the main implementation of two functions: 1, upload a single file and move it to the corresponding upload directory, 2, upload multiple files at once and store them in the specified folder, next we step by step implementation. 2-Create a project
    • File/new/other.


Input:

    • Group ID:com.yiibai
    • Artifact Id:springmvcfileupload
    • Package:com.yiibai.springmvcfileupload


In this way, the project is created, as shown in:


Do not worry about an error message when the project is created. The reason is that you have not yet declared the servlet library.

Attention:

Eclipse 4.4 (Luna) may have an error creating a Maven project structure and need to fix it.
3-Configuring MAVEN
    • 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/maven-v4_0_0.xsd" > <modelversion >4.0.0</modelVersion> <groupId>com.yiibai</groupId> <artifactid>springmvcfileupload </artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name >springmvcfileupload Maven webapp</name> <url>http://maven.apache.org</url> <dependencies&        Gt            <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> & lt;! --Jstl for JSP page--<!--Http://mvnrepository.com/artifact/javax.servlet/jstl--<dependen            Cy> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--JSP API--<!--http://m Vnrepository.com/artifact/javax.servlet.jsp/jsp-api-<dependency> &LT;GROUPID&GT;JAVAX.SERVL Et.jsp</groupid> <artifactId>jsp-api</artifactId> &LT;VERSION&GT;2.2&LT;/VERSION&G            T <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.springframewor K/spring-web-<dependency> <groupId>org.springframework</groupId> &lt ;artifactid>spring-web</artifactid> <version>4.1.4.RELEASE</version> </dependenc             Y> <!--HTTP://MVNREPOSITORY.COM/ARTIFACT/ORG.SPRINGFRAMEWORK/SPRING-WEBMVC-<dependency> <groupId>org.springframework</groupId> &LT;ARTIFACTID&GT;SPRING-WEBMVC&LT;/ARTIFACTID&G            T        <version>4.1.4.RELEASE</version> </dependency> <!--Apache Commons FileUpload-- <! --Http://mvnrepository.com/artifact/commons-fileupload/commons-fileupload <dependency> &lt            ;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>common S-io</groupid> <artifactId>commons-io</artifactId> <version>2.4</version&        Gt </dependency> </dependencies> <build> <finalname>springmvcfileupload</finalname&gt        ; <plugins> <!--config:maven Tomcat Plugin--<!--HTTP://MVNREPOSITORY.COM/ARTIFAC T/org.apache.tomcat.maven/tomcat7-maven-plugin-<plugin> <groupid>org.apache.t OmCat.maven</groupid> <artifactId>tomcat7-maven-plugin</artifactId> <vers Ion>2.2</version> <!--Config:contextpath and Port (Default-/springmvcfileu pload:8080)-<!--<configuration> <p                Ath>/</path> <port>8899</port> </configuration> -</plugin> </plugins> </build> </project>
4-Configure Spring


Configure Web. Xml.

Springcontextlistener will read the parameters contextconfiglocation in the configuration file:
    • Web-inf/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-n Ame>spring-mvc</servlet-name> <servlet-class> Org.springframework.web.servlet.DispatcherSer Vlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet -mapping> <servlet-name>spring-mvc</servlet-name> <url-pattern>/</url-pattern> &L T;/servlet-mapping> <!--other XML Configuration--<!--Load by Spring Contextloaderlistener--& Lt;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>
To configure Spring MVC:
    • Web-inf/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/spri Ng-mvc-4.1.xsd "> <!--Package Scan--<context:component-scan base-package=" COM.YIIBAI.SPRINGMVCFILEUPL Oad "/> <!--enables the Spring MVC Annotation Configuration--<context:annotation-config/> &L T;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.CommonsMulti  Partresolver > <!--Maximum file SIZE:1MB-and <!--1MB = 125000 Byte-to-<property Name= "Maxuploadsize" value= "125000"/> </bean> </beans>
    • Web-inf/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>
5-java class
    • Myfileuploadcontroller.java
Package com.yiibai.springmvcfileupload; 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;    @Controllerpublic class Myfileuploadcontroller {//Upload one File. @RequestMapping (value = "/uploadonefile") public String Uploadonefilehandler () {//Forward to "/web-inf/pages/u        Ploadonefile.jsp ".    return "Uploadonefile";    }//Upload Multi File. @RequestMapping (value = "/uploadmultifile") public String Uploadmultifilehandler () {//Forward to "/web-inf/pag        Es/uploadmultifile.jsp ". Return "UPLOADMULtifile ";    }//uploadonefile.jsp, uploadmultifile.jsp submit to. @RequestMapping (value = "/doupload", method = requestmethod.post) public String Uploadfilehandler (HttpServletRequest re        Quest, 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 is 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 the 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"; } }
6-View (JSP)
    • uploadonefile.jsp
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "    pageencoding=" UTF-8 "%>
    • uploadmultifile.jsp
<%@ page language= "java" contenttype= "text/html; Charset=utf-8" pageEncoding= "UTF-8"%>
    • 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 "%>     
7-Run the application first, before you run the application, you need to build the entire project. Right-click the project and select:

Run Configuration:
Input:
    • Name:run Springmvcfileupload
    • Base directory: ${workspace_loc:/springmvcfileupload}
    • Goals:tomcat7:run





Click Run:

    • Http://localhost:8080/SpringMVCFileUpload/uploadOneFile


    • Http://localhost:8080/SpringMVCFileUpload/uploadMultiFile

      A

Spring MVC File Upload Tutorial

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.