Springmvc file upload and download implementation

Source: Internet
Author: User

SPRINGMVC supports file uploads through the Multipartresolver (multipart parser) object.

Multipartresolver is an interface object that needs to be implemented by its implementation class Commonsmultipartresolver to perform file upload work.

1. Use the Multipartresolver object to configure the Bean in XML.

1<?xml version= "1.0" encoding= "UTF-8"?>2<beans xmlns= "Http://www.springframework.org/schema/beans"3Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"4xmlns:context= "Http://www.springframework.org/schema/context"5Xsi:schemalocation= "Http://www.springframework.org/schema/beans6http//www.springframework.org/schema/beans/spring-beans-4.3.xsd7http//Www.springframework.org/schema/context8http//www.springframework.org/schema/context/spring-context-4.3.xsd ">9<context:annotation-config/>Ten<context:component-scan base- Package= "Com.wxy.controller"/> One<bean id= "Viewresolver"class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" > A<property name= "prefix" value= "/web-inf/jsp/" ></property> -<property name= "suffix" value= ". JSP" ></property> -</bean> the     <bean id= "multipartresolver" class= " Org.springframework.web.multipart.commons.CommonsMultipartResolver">16 <property name=" Defaultencoding "value=" UTF-8 "/>17 <property name=" maxuploadsize "value=" 2097152 "/>18 </bean>  +</beans>

2.fileupload.jsp upload Page

1<%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>234<title> File Upload </title>5<script>6<%--decide whether to fill in the descendants and have chosen to upload files--%>7 function Check () {8var name = document.getElementById ("name"). Value ();9var name = document.getElementById ("File"). Value ();Ten             if(name== ""){ OneAlert ("Please fill in the Descendants"); A                 return false; -             } -             if(file.length==0| | file== ""){ theAlert ("Please select Upload file"); -                 return false; -             } -             return true; +         } -</script> + A<body> at<%--enctype= "Multipart/form-data" uses a binary stream to process form data--%> - <form action= "${pagecontext.request.contextpath}/fileupload.action" method= "post" enctype= "multipart/ Form-data "onsubmit=" return Check () ">25 uploader: <input id=" name "type=" text "name=" name "/><br/>26 Please select File : <input id= "file" type= "file" Name= "UploadFile" multiple= "multiple"/><br/>27 <%-- Multiple properties Select multiple file uploads--%>28 <input type= "Submit" value= "File Upload"/>29 </form> -</body> to

3.filedownload.jsp download page

  1  <%@ page contenttype= "Text/html;charset=utf-8" language= "Java" pageencoding= "UTF-8"%> 2  <%@ page import  = "Java.net.URLEncoder"%> 3   4   5  <meta http-equiv= " Content-type "content=" text/html; Charset=utf-8 "> 6  <title> file Download </title>  7   8  <body> 9  <a href= "${pagecontext.request.contextpath}/ Download.action?filename=<%=urlencoder.encode ("image. txt", "UTF-8")%> "> File download </a>  10  </body>11  

4.fileuploadanddownloadcontroller.java file Upload and download controller class

1  PackageCom.wxy.controller;2 3 Importorg.apache.commons.io.FileUtils;4 Importorg.springframework.http.HttpHeaders;5 ImportOrg.springframework.http.HttpStatus;6 ImportOrg.springframework.http.MediaType;7 Importorg.springframework.http.ResponseEntity;8 ImportOrg.springframework.stereotype.Controller;9 Importorg.springframework.web.bind.annotation.RequestMapping;Ten ImportOrg.springframework.web.bind.annotation.RequestParam; One ImportOrg.springframework.web.multipart.MultipartFile; A  - Importjavax.servlet.http.HttpServletRequest; - ImportJava.io.File; the ImportJava.net.URLEncoder; - Importjava.util.List; - ImportJava.util.UUID; -  +@Controller ("Controller") -  Public classFileuploadanddownloadcontroller { +@RequestMapping ("/tofileupload") A      PublicString toupload () { at         return"FileUpload"; -     } -@RequestMapping ("/tofiledownload") -      PublicString todownload () { -         return"Download"; -     } in@RequestMapping ("/fileupload.action") -      PublicString Handleformupload (@RequestParam ("name") String name, to@RequestParam ("UploadFile") list<multipartfile>UploadFile, httpservletrequest request) { +         if(!uploadfile.isempty () && uploadfile.size () > 0) { -              for(Multipartfile file:uploadfile) { theString OriginalFilename =file.getoriginalfilename (); *String Dirpath = Request.getservletcontext (). Getrealpath ("/upload/"); $File FilePath =NewFile (dirpath);Panax Notoginseng                 if(!filepath.exists ()) { - filepath.mkdirs (); the                 } +  AString NewFileName = name + "_" +OriginalFilename; the                 Try { +File.transferto (NewFile (Dirpath + "_" +newfilename)); -}Catch(Exception e) { $ e.printstacktrace (); $                     return"Error"; -                 } -             } the             return"Success"; -}Else {Wuyi             return"Error"; the         } -     } Wu@RequestMapping ("/download.action") -      Publicresponseentity<byte[]> filedownload (httpservletrequest request,string filename)throwsexception{ AboutString path = Request.getservletcontext (). Getrealpath ("/upload"); $File File =NewFile (path+file.separator+filename); -filename = This. GetFileName (request,filename); -Httpheaders headers =Newhttpheaders (); -Headers.setcontentdispositionformdata ("Attachment", filename); A Headers.setcontenttype (mediatype.application_octet_stream); +         return Newresponseentity<byte[]>(Fileutils.readfiletobytearray (file), headers, httpstatus.ok); the     } -      PublicString getfilename (httpservletrequest request,string filename)throwsexception{ $String[] Iebrowserkeyword = {"MSIE", "Trident", "Edge"}; theString useragent = Request.getheader ("User-agent"); the          for(String keyword:iebrowserkeyword) { the             if(Useragent.contains (KeyWord)) { the                 returnUrlencoder.encode (filename, "UTF-8"); -             } in         } the         return NewString (Filename.getbytes ("UTF-8"), "Iso-8859-1"); the     } About}
Fileuploadanddownloadcontroller

Springmvc file upload and download implementation

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.