Use SPRINGMVC to implement file upload and download environment configuration and upload __java file upload and download

Source: Internet
Author: User
Recent projects have used file upload and download functions, and task assignments are done at the same time. Now that the project is over, I think this function is more important, so deliberately extracted it out of its own to try.


First, the basic configuration:

MAVEN Guide Package and Configuration Pom.xml, when the package is based on the springmvc of the base, you need to import files to upload the download COMMONS-IO.JSR and Commons-fileupload.jar:
<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>filLoadTest</groupId> <artifactid>filloadtest</ artifactid> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name> Filloadtest Maven webapp</name> <url>http://maven.apache.org</url> <build> <finalname& Gt;filloadtest</finalname> <plugins> <!--The following configuration guarantees that the JRE version will not change each time you force an update, my Eclipse4.4.1,maven 3.2.5 For example, if you do not set this, the JRE will change back to 1.5--> <plugin> <artifactid>maven-compiler-p each time you force an update  
                    Lugin</artifactid> <version>2.3.2</version> <configuration>  <source>1.7</source>
                    <target>1.7</target> <encoding>UTF-8</encoding> <compilerArguments> <verbose/> <bootcla  
                Sspath>${java.home}\lib\rt.jar</bootclasspath> </compilerArguments> 
    </configuration> </plugin> </plugins> </build> <dependencies>
      <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId>
    	<version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <v ersion>4.0.6.release</version> </dependency> <dependency> &LT;GROUPID&GT;COM.FASTERXML.J ackson.core</groupid&Gt <artifactId>jackson-annotations</artifactId> <version>2.2.3</version> </dependency&gt
    ; <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactid>jackson-core</ artifactid> <version>2.2.3</version> </dependency> <dependency> &LT;GROUPID&G T;com.fasterxml.jackson.core</groupid> <artifactId>jackson-databind</artifactId> &LT;VERSION&G t;2.2.3</version> </dependency> <dependency> <groupid>commons-fileupload</groupid&
    	Gt 
    <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactid>commons-io</artifactid&gt
    	; <version>2.4</version> </dependency> </dependencies> </project>


Web.xml Base configuration:
<?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 > <filter> <description> Character set filter </description> <filter-name>encodingfil Ter</filter-name> <filter-class>org.springframework.web.filter.characterencodingfilter</ Filter-class> <init-param> <description> Character Set code </description> <param-name>encoding</p aram-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping&
		Gt <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </ Filter-mapping> <servlet> <servlet-name>springmvc</servLet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-va lue>classpath:spring.xml</param-value> </init-param> </servlet> <servlet-m Apping> <servlet-name>springMVC</servlet-name> <url-pattern>*.do</url-pattern&  
    Gt </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <w Elcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-fil E>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>   Default.jsp</welcome-file> </welcome-file-list> </web-app>


Spring Base configuration Spring.xml:
<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:x Si= "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:sch emalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans /spring-beans-3.0.xsd Http://www.springframework.org/schema/context HTTP://WWW.SPRINGFRAMEWORK.ORG/SC Hema/context/spring-context-3.0.xsd Http://www.springframework.org/schema/mvc http://www.springframework. Org/schema/mvc/spring-mvc.xsd "> <context:annotation-config/> <mvc:annotation-driven/> & Lt;context:component-scan base-package= "Controllers"/> <!--avoid IE to execute AJAX when the return JSON appears download file--> <bean "M AppingjacksonhttpmessageconvErter "class=" Org.springframework.http.converter.json.MappingJackson2HttpMessageConverter "> <property name= "Supportedmediatypes" > <list> <value>text/html;charset=utf-8</value> </list> </p Roperty> </bean> <!--start the annotation feature of spring MVC, complete the mapping of request and annotation Pojo--> <bean class= "Org.springframework.web.s
				Ervlet.mvc.annotation.AnnotationMethodHandlerAdapter "> <property name=" messageconverters "> <list> <ref bean= "Mappingjacksonhttpmessageconverter"/><!--JSON converter--> </list> </property> </b Ean> <!--support uploading files--> <bean id= "Multipartresolver" class= . Commonsmultipartresolver "> <!--100M--> <property name=" maxuploadsize "value=" 104857600 "></proper  
 ty> <property name= "defaultencoding" value= "Utf-8" ></property> </bean> </beans>


Second, the File upload code

To upload a simple page index.html, pay attention to the setting of the Entype when form forms submit:
<! DOCTYPE html>


Upload the corresponding background Java code, specific questions see comments:
Package controllers;
Import Java.io.File;
Import java.io.IOException;
Import Java.util.Iterator;
Import Javax.servlet.http.HttpServletRequest;
Import Org.apache.commons.io.FileUtils;
Import Org.springframework.http.HttpHeaders;
Import Org.springframework.http.HttpStatus;
Import Org.springframework.http.MediaType;
Import org.springframework.http.ResponseEntity;
Import Org.springframework.stereotype.Controller;
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;
Import Org.springframework.web.multipart.MultipartHttpServletRequest;


Import Org.springframework.web.multipart.commons.CommonsMultipartResolver; @Controller public class Filecontroller {/** * File Upload * * @author: Tuzongxun * @Title: UploadFile * @param @pa Ram file * @param @param request * @param @throws Illegalstateexception * @param @throws IOException * @return void * @date APR, 2016 1:22:00 PM * @throws */@RequestMapping (Valu E = "/uploadfile.do", method = requestmethod.post) public void UploadFile (HttpServletRequest request) throws Illegalst Ateexception, IOException {//@RequestParam ("file") multipartfile file, commonsmultipartresolver multipartresolver =
		New Commonsmultipartresolver (Request.getsession (). Getservletcontext ()); To determine if the request has file uploads, that is, the multi-part Requests if (Multipartresolver.ismultipart (Request)) {///convert to multiple parts of the petition Multiparthttpservletre
			Quest Multirequest = (multiparthttpservletrequest) request;
			Get all the filenames in the request iterator<string> iter = Multirequest.getfilenames ();
				while (Iter.hasnext ()) {//Get uploaded file Multipartfile f = multirequest.getfile (Iter.next ());
					if (f!= null) {//Get the file name of the current upload file String myfilename = F.getoriginalfilename (); If the name is not "", the file exists, otherwise the file does not exist if (Myfilename.trim ()!= "") {//define upload path StRing Path = "c:\\users\\tuzongxun123\\desktop\\" + myfilename;
						File LocalFile = new file (path);
					F.transferto (LocalFile); }
				}
			}
		}
	}
}


The page effect chart looks like this, and when you select a file to submit, you will see that the selected file is uploaded to the location specified in the code, which is on my desktop.


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.