Springmvc upload download function refer to the online code to write a simple example
1, need to import jar package: Ant.jar, Commons-fileupload.jar, Connom-io.jar. Of course spring jar package is indispensable oh I'm using spring+springmvc+hibernate can go to the official website directly download Springmvcjar can
2. Springmvc.xml Configuration
<?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: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.xsdhttp://www.springframework.org/schema/ contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/ Schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd "><!--Scan Package--><context: Component-scan base-package= "Com.ai.customer"/> <!--start annotations-<mvc:annotation-driven/><!--file Upload--& Gt <bean id= "Multipartresolver" class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" > <!--set the maximum size of the uploaded file to 10MB-<property name= "Maxuploadsize" > <VALUE>10000000</VALUE> </property> </bean> <!--static file access-<mvc:default-servlet-handler/> <!--resolution of the Model view name, in the model view Name add-front-to-<bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" > <property Name= "prefix" value= "/"/> <property name= "suffix" value= ". jsp"/> </bean> </beans>
3. Web. XML configuration
<servlet> <servlet-name>spring</servlet-name> <servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class> <init-param> <param-name> Contextconfiglocation</param-name> <param-value>classpath*:config/spring/spring-*.xml</ param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet- mapping> <servlet-name>spring</servlet-name> <url-pattern>*.do</url-pattern> </ Servlet-mapping><filter> <filter-name>codeUTF-8</filter-name> <filter-class> Org.springframework.web.filter.characterencodingfilter</filter-class> <init-param> <param-name >encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param > <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>codeutf-8</filter-name > <url-pattern>/*</url-pattern> </filter-mapping>
4. Program code block
Package Com.ai.customer.controller;import Java.io.bufferedinputstream;import Java.io.bufferedoutputstream;import Java.io.file;import Java.io.fileinputstream;import Java.io.ioexception;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.commons.fileupload.fileupload;import Org.apache.commons.io.fileutils;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestparam;import Org.springframework.web.multipart.MultipartFile; Import Org.springframework.web.servlet.ModelAndView, @Controllerpublic class Fileuploadcontroller {/* * File Upload in Springmvc * @ First step: Because SPRINGMVC uses the Commons-fileupload implementation, its components are introduced into the project * @ Here are the Commons-fileupload-1.2.1.jar and Commons-io-1.3.2.jar * @ Step Two: Configure the Multipartresolver processor in SPRING-MVX. You can add property restrictions for uploaded files here * <bean id= "multipartresolver" * class= " Org.springframework.web.multipart.commons.CommonsMultipartResolver "> * <!--set the maximum size of the uploaded file to 10MB-<property name= "Maxuploadsize" > * <value>10000000< ;/value> * </property> * </bean> * Step three: Add the Multipartfile parameter to the controller's method. This parameter is used to receive the contents of the file component in the form * Step Fourth: Write the foreground form. Note enctype= "Multipart/form-data" and <input type= "file" name= "* * * *"/> * If it is a single file directly using Multipartfile *//*********** Upload Code **************************/@RequestMapping ("/upload.do") public Modelandview upload (String name,// Upload Multiple Files @requestparam ("file") multipartfile[] File,httpservletrequest request) throws IllegalStateException, IOException {//Gets the file storage location string realpath = Request.getsession (). Getservletcontext (). Getrealpath ("/uploadfile"); File Pathfile = new file (Realpath), if (!pathfile.exists ()) {//folder does not exist to create files Pathfile.mkdirs ();} for (Multipartfile f:file) {System.out.println ("File type:" +f.getcontenttype ()); System.out.println ("File name:" +f.getoriginalfilename ()); SYSTEM.OUT.PRINTLN ("File Size:" +f.getsize ()); System.out.println ("..........")...);//upload the file copy to the server F.transferto (new file (Realpath + "/" + F.getoriginalfilename ())), and then click on the "/"/"*" button. fileutils.copy}//get Modelandview object Modelandview view = new Modelandview (); View.setviewname ("redirect:index.jsp"); return view;} /******** download Code *************/@RequestMapping (value = "download.do") public modelandview Download (httpservletrequest Request, HttpServletResponse response) throws Exception {//String StoreName = "spring3.xapi_zh.c HM "; String storename= "Premises", ". txt"; String ContentType = "Application/octet-stream"; Fileuploadcontroller.download (Request, Response, StoreName, ContentType); return null; }//File download Main method public static void download (HttpServletRequest request, HttpServletResponse Res Ponse, String storeName, String contentType) throws Exception {request.setcharacterencoding ("utf- 8 "); Bufferedinputstream bis = null; BufferedoutputStream BOS = NULL; Gets the project root directory String Ctxpath = Request.getsession (). Getservletcontext (). Getrealpath (""); Get download file off shoulder String Downloadpath = ctxpath+ "/uploadfile/" + storeName; Gets the length of the file long filelength = new file (downloadpath). Length (); Set file output Type Response.setcontenttype ("Application/octet-stream"); Response.setheader ("Content-disposition", "attachment; Filename= "+ New String (Storename.getbytes (" Utf-8 ")," iso8859-1 ")); Set the output length Response.setheader ("Content-length", String.valueof (Filelength)); Gets the input stream bis = new Bufferedinputstream (new FileInputStream (Downloadpath)); Output stream bos = new Bufferedoutputstream (Response.getoutputstream ()); byte[] buff = new byte[2048]; int bytesread; while ( -1! = (bytesread = bis.read (buff, 0, buff.length))) {bos.write (buff, 0, bytesread); } //close Flow bis.close (); Bos.close (); } }
5. JSP page codeNote: The properties of the form form in the setup form are: enctype= "Multipart/form-data"
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 " pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Springmvc Upload and download