Spring file upload, including selecting multiple files at once

Source: Internet
Author: User
Tags save file

Background:

Http://www.cnblogs.com/lixuwu/p/8495275.html has implemented a single file upload and download, multi-file upload is another scenario, recorded here

Implementation process

First, the front desk. This is what happens when you run it. A very simple form page, two file upload button, one commit

Where a single file is uploaded, that is, only one file can be selected and multiple



In contrast, multiple files can select multiple files at the same time.

This is the way the file is chosen.

Foreground settings

The code is as follows: a form, the file upload is a <input> input, the attribute type= "file". You can only select a single file at this time. You can select multiple files at the same time by adding a multiple

JSP page multifile.jsp:

<%@ 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 "><HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"><title>Insert Title here</title></Head><Body>      <formAction= "${pagecontext.request.contextpath}/test/upload"enctype= "Multipart/form-data"Method= "POST">Single File:<inputtype= "File"name= "Filetest"><BR/>Multiple Files:<inputtype= "File"name= "FileList"multiple/></br/>          <inputtype= "Submit"value= "Submit" />      </form>  </Body></HTML>

File control beans in spring:

 PackageSpring.boot.uploadfile.config;Importjavax.servlet.MultipartConfigElement;Importorg.springframework.boot.web.servlet.MultipartConfigFactory;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Configuration;ImportOrg.springframework.context.annotation.ImportResource;/*** Classname:configclass <br/> * Function:todo <br/> * date:2018 year March 2 afternoon 8:20:05 <br/> *@authorPrd-lxw *@version1.0 *@sinceJDK 1.7 *@see       *//*** classpath path: locations={"Classpath:application-bean1.xml", "Classpath:application-bean2.xml"} * File path: Locations = {"File:d:/test/application-bean1.xml"}; */@Configuration @importresource (Locations= {"Classpath:spring-web.xml" })//@ImportResource (locations={"File:d:/test/application-bean1.xml"}) Public classConfigclass {@Bean Public multipartconfigelement multipartconfigelement() {Multipartconfigfactory factory=Newmultipartconfigfactory (); //file MaxFactory.setmaxfilesize ("1000240KB");//KB,MB        ///Set Total upload data total sizeFactory.setmaxrequestsize ("102400KB"); returnFactory.createmultipartconfig (); }}

Background code

Controller Layer Code:

/*** Project name:uploadfile * File Name:MutilFileUploadController.java * Package Name: Spring.boot.uploadfile.controller * date:2018 March 2 Afternoon 9:50:25 * Copyright (c) 2018, Shenzhen financial Electronic Settlement Center all rights Reserved. **/ PackageSpring.boot.uploadfile.controller;ImportJava.io.File;Importjava.io.IOException;ImportJava.util.Iterator;Importjava.util.List;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.ResponseBody;ImportOrg.springframework.web.multipart.MultipartFile;Importorg.springframework.web.multipart.MultipartHttpServletRequest;/*** Classname:mutilfileuploadcontroller <br/> * Function:todo <br/> * date:2018 March 2 afternoon 9:50:25 <b R/> *@authorPrd-lxw *@version1.0 *@sinceJDK 1.7 *@see       *//*** File upload test class*/@Controller @requestmapping ("/test") Public classMutilfileuploadcontroller {@RequestMapping ("Multi")     PublicString Multiindex () {return"Multifile"; } @ResponseBody @RequestMapping (value= "Upload")     Public voidTestupload (Multiparthttpservletrequest request)throwsIOException {/** Multiparthttpservletrequest: Inherited from HttpServletRequest and Multipartrequest. * The related access operations are defined in Multipartrequest. Multiparthttpservletrequest overrides the method in the HttpServletRequest and extends it. If you receive the number of parameters in HttpServletRequest, you need to convert it to multiparthttpservletrequest type * multiparthttpservletrequest reque          St = (multiparthttpservletrequest) httpservletrequest; */        /** Again back to the form, let's say we uploaded the file 1 in a single file marquee, multiple file boxes uploaded files 2, 3, 4.          * Then for the background received, can be so understood, is a map of the form (in fact, its backstage really is stored in map). * What is the key to this map? is the name= "" attribute in the <input> tag above. Value is the * file we just uploaded, as shown in the following example, each value is a list containing a collection of corresponding files * * uploaded to the background to receive the map is this: * file          Test: File 1 * fileList: File 2, File 3, file 4 * * Although the file name is obtained from the surface meaning of the method name, the filename is actually not related to the uploaded file itself. * Just said that the key of this map is the name= "" attribute in the <input> tag, so the value of this property is given .*/Iterator<String> FileNames =Request.getfilenames ();  while(Filenames.hasnext ()) {//put the values out of the filenames collection.String FileName =Filenames.next (); System.out.println ("FileName:" +fileName); /** the Request.getfiles (filename) method is to get the corresponding file * Collection list by using the filename key. Just in this map, the files are packaged into multipartf Ile Type*/List<MultipartFile> fileList =request.getfiles (fileName); if(Filelist.size () > 0) {                //Traverse file ListIterator<multipartfile> Fileite =Filelist.iterator ();  while(Fileite.hasnext ()) {//get every fileMultipartfile Multipartfile =Fileite.next (); //get the original file nameString OriginalFilename =Multipartfile.getoriginalfilename (); System.out.println ("OriginalFilename:" +originalfilename); //sets the save path. String Path = "E:\\testjava\\filesss"; //check that the directory that corresponds to the path exists. Create a directory if it does not existFile dir =NewFile (path); if(!dir.exists ())                    {Dir.mkdirs (); } String FilePath= path + File.separator +OriginalFilename; System.out.println ("FilePath:" +FilePath); //Save FileFile dest =NewFile (FilePath); if(!(Dest.exists ())) {                        /** Multipartfile provides the void TransferTo (file dest) method, which transfers the retrieved file to the                          Specifies the path. */Multipartfile.transferto (dest); /** If additional action is required for the file, Multipartfile also provides a * InputStream getInputStream () method to obtain Fetch the input stream of the file * * For example the following statement is passed * org.apache.commons.i                          * void Copyinputstreamtofile provided by o.fileutils (InputStream source, File destination) * method, gets the input stream and saves it to the specified path*/                        //Fileutils.copyinputstreamtofile (Multipartfile.getinputstream (), dest);                     }                    //Multipartfile also provides some other ways to get some of the properties of a file//Get file ContentTypeString ContentType =Multipartfile.getcontenttype (); System.out.println ("ContentType:" +ContentType); /** Get name * Actually this name is the same as the GetFileName value mentioned above, * is the key in the map The value. That is, the front page <input> name= "" * property. But the above GetFileName just get the key to the map, * and spring will log the value in the name attribute * to each of the corresponding files when processing the upload file. If you need to get this * value from the file level, you can use this method*/String name=Multipartfile.getname (); System.out.println ("Name:" +name); //get file size in bytes                    LongSize =multipartfile.getsize (); System.out.println ("Size:" +size); System.out.println ("---------------------------------------------------"); }            }        }    }}
View Code

PS: The above note is simple, the control of the implementation can be

(go) spring file upload, including selecting multiple files at once

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.