Springmvc File Upload and download

Source: Internet
Author: User

This blog will explain the Springmvc file upload and download features. For the upload function, we are often used in the project, such as user registration, upload the user's avatar, this time will be used to upload the function. For the download, the use of the scene is also very common, such as our project has a description of the use is a PDF version, will provide users with the ability to download. As opposed to speaking, these two functions are very common, not much nonsense to say, according to the Convention, we first look at the directory of this blog.

Directory

A: Build SPRINGMVC development environment

Second: To achieve the function of file upload

Third: Bind the upload file to a specific object

Four: Realize the user download function

V: summary

A: Build SPRINGMVC development environment

First we create a new Web project in MyEclipse, named: springmvcfileupload. Then import the necessary jar packages, where the jar packages are mainly spring jar packages and another very important jar package with the name: Commons-fileupload-1.3.1.jar, this is a toolkit developed by Apache specifically for uploading files, which presets a lot of file upload API for us to use, and then create a new package in the SRC directory, Named Com.wyq.Controller and Com.wyq.domain. Two packages are used to store the controller and domain model respectively. Then in the Webroot directory to create a new folder, named JSP, mainly used to store our JSP page, Next, configure the Web. xml file, where it is configured on the link of our SPRINGMV control dispatcher to process the client request, and then create a new Springmvc-config file, mainly configuring the Springmvc bean, In addition to the need to configure the view parser to parse the view resources and basic scan package, but also need to configure a very important bean, the bean's name is "Multipartresolver", mainly for processing files, where the properties can be configured to upload the file size and encoding, Let's take a look at the code for the configuration file:

Web. xml file:

      <!--SPRINGMVC control Dispenser--
<servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class >org.springframework.web.servlet.dispatcherservlet</servlet-class> <init-param > <param-name>contextConfigLocation</param-name> <param-value>classpath: springmvc-config.xml</param-value> </init-param> <load-on-startup>1</ load-on-startup> </servlet> <servlet-mapping> <servlet-name> springdispatcherservlet</servlet-name> <url-pattern>/</url-pattern> </ Servlet-mapping>

Springmvc-config.xml:

  <context:component-scan base-package = "Com.wyq"/>    <!--configuration View Resolver--    <bean id= " Viewresolver "        class=" Org.springframework.web.servlet.view.InternalResourceViewResolver ">        <property name= "prefix" value= "/web-inf/page/" ></property>        <property name= "suffix" value= ". JSP" ></property>    </bean>        <bean id= "Multipartresolver"        class= " Org.springframework.web.multipart.commons.CommonsMultipartResolver ">
<!--maximum size of uploaded files > <property name= "maxuploadsize" value= "17367648787" ></property>
       

</bean>

Second: To achieve the function of file upload

2.1: First, we will create a new JSP page, named: uploadform.jsp Write an uploaded page form form, it is important to note that the form's properties are added entcypt= "Multipart/form-data", This means that the upload will be a binary stream format, uploaded in the specified binary, easy for the server to process, using the POST request:

<body>    <form action= "gotoaction" enctype= "Multipart/form-data" method= "POST" >        <table>            <tr>                <td> Please select File:</td>                <td><input type= "Files" name= "file" ></td>            </tr>            <tr>                <td> start uploading </td>                <td><input type= "Submit" value= "Upload" ></td>            </tr>        </table>    </form></body>

2.2: Then write a successful upload JSP page, mainly used when uploading the success of the page to jump, named: success.jsp

  <body>   

2.3: Then write a failed upload page, mainly used when the upload failed to jump when the page, named: error.jsp

<body>

2.4: Write the JSP page, the next is to write our controller, SPRINGMVC Controller, Write a Fileuploadcontroller class in our Com.wyq.Controller, and then write the specific code, as shown below, noting that using Multipartfile to accept the file file only son come from the form table, Multipartfile has several core API, which can be used by us, such as Boolean isEmpty (), to determine if a file is empty. void TransferTo (file file), which writes files to the destination path address.

@Controller Public classFileuploadcontroller {@RequestMapping (value= "/{formname}")     Publicstring LoginForm (@PathVariable string formName) {returnFormName; } @RequestMapping (Value= "/gotoaction", method=requestmethod.post) PublicString Upload (@RequestParam ("File") multipartfile file, HttpServletRequest request) {if(!File.isempty ()) {String ContextPath= Request.getcontextpath ();//"/springmvcfileupload"String Servletpath = Request.getservletpath ();//"/gotoaction"String scheme = Request.getscheme ();//"http"       String Storepath= "E:\\project\\springmvcfileupload\\webroot\\images";//Store the file path we uploaded String FileName=File.getoriginalfilename (); File filepath=NewFile (Storepath, fileName); if(!Filepath.getparentfile (). exists ()) {Filepath.getparentfile (). mkdirs ();//If directory does not exist, create directory}Try{File.transferto (NewFile (storepath+file.separator+fileName)); /write file to destination file address}Catch(Exception e) {e.printstacktrace (); return"Error"; }            return"Success";//Return to Success page}Else {            return"Error";//Return to the failed page}}

2.5: Well, to this we can implement the upload function, published in the Tomact container, and then you can upload files. In the browse input: Http://localhost:8080/SpringMvcFileUpload/uploadForm specific page request below, then browse the specific file, click the upload button:

Select the file, click Upload

To this step is not finished, we look down, there is no write to the target folder, that is, in the D:\userUploadFile\Files directory to see if there is my upload file, to see that there is a correct write

Third: bind the upload file to a specific object

3.1: First we define an entity class user, the primary function of the Headimage attribute in this entity class is to map the file we upload, and we can see that it is of the Multipartfile type:

 Public class Implements serializable{// User entity class        private  String userName;         Private Multipartfile Headimage; // the upload file is automatically bound to this       property // omit getter and setter methods }

3.2: Then write our JSP upload page, here we are to simulate a user register upload avatar scene, create a new registerform.jsp page, and then write a form form, as follows:

<body>    

3.3: Write Our method The controller handles the code for the layer of the registered logic, noting that the user object is added to the @modelattribute annotation, whose main purpose is to map the Headimage attribute of the form form above into the object automatically, and map< String,object> map is mainly to store the user object, placed in the requestscope inside, so that the El expression can be used to remove the value.

@RequestMapping (value= "/register", method=requestmethod.post) PublicString Reg (@ModelAttribute User user,httpservletrequest request,map<string,object>map) {        FinalString wrong= "Error"; FinalString good= "Success"; Multipartfile Headimage=User.getheadimage (); BooleanEmpty =Headimage.isempty (); if(!empty) {String Realpath= Request.getservletcontext (). Getrealpath ("/images"); String Uploadpath= "D:\\useruploadfile\\files"; String Headimagename=Headimage.getoriginalfilename (); File ImageFile=NewFile (uploadpath,headimagename); Try{Headimage.transferto (NewFile (uploadpath+file.separator+headimagename)); } Catch(Exception e) {e.printstacktrace (); returnwrong; } map.put ("User", user);            return"UserInfo"; }Else {            returnwrong; }    }

3.4: We have to create a new JSP page, named userinfo.jsp, its main function is to display just our file name:

<body> user picture: ${requestscope.user.headimage.originalfilename}</body>

3.5: Page finished, we are here to simulate the test, in the client IE browser, enter Http://localhost:8080/SpringMvcFileUpload/registerForm:

Four: Realize the user download function

4.1: First we have to change the userinfo.jsp page, the main purpose is to turn it into a download connection, and then we can write our controller to handle the HREF request. It can be seen that we use the EL expression to pass the URL to the next controller, which the controller can take out to handle:

<body>      a        href= "download?filename=${ RequestScope.user.headimage.originalFilename} ">         user picture: ${requestscope.user.headimage.originalfilename }      </a> </body>

4.2: Take a look at our download controller code: Note that the download method returns the Responseentity<byte[]> type, which is the encapsulated return type, which we need to pass in a byte array, headers, Httpstatus, then it will return to the specific download stream, calling the client to download the resource

@RequestMapping (value= "/download", method=requestmethod.get)//Match the download request in the href Publicresponseentity<byte[]> Download (httpservletrequest request, @RequestParam ("filename") String filename, model model)throwsioexception{String Downloadfilepath= "D:\\useruploadfile\\files";//To fetch the file file from our upload folder=NewFile (Downloadfilepath+file.separator+filename);//Create a new filehttpheaders Headers=NewHttpheaders ();//HTTP Header InformationString DownloadFileName=NewString (Filename.getbytes ("UTF-8"), "iso-8859-1");//Set EncodingHeaders.setcontentdispositionformdata ("Attachment", DownloadFileName);                Headers.setcontenttype (Mediatype.application_octet_stream); //mediatype: Internet media type contentType: Media type information in a specific request                return Newresponseentity<byte[]>(Fileutils.readfiletobytearray (file), headers,httpstatus.created); }

4.3: Let's test if the writing can run correctly, click the hyperlink, note the link to the address: http://localhost:8080/SpringMvcFileUpload/download?filename= " Myheadimage ". jpg, this means that the link will go to request the controller, and then the controller to process the download, so that the download function of the file is completed:

Click the hyperlink:

V: summary

This blog post introduces the functions of Springmvc uploads and files, which should be noted for the use of the file upload package Common-fileupload.jar package, as well as configuring Mulitipartresolver this bean on the configuration file. The following also introduces the use of Java entity class to map the properties of the uploaded file corresponding file, this is the advantage of it will automatically map, and then put the object into our request domain, you can display to the interface user layer, which is the embodiment of the MVC thought pattern. Next is the introduction to download the file, only need to remove the file from the target address of our write, and then carry out the encapsulation of the Responseentity object, we can implement the download function

Resources

"Spring+mybatis Enterprise Application Practical"

Springmvc File Upload and download

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.