SPRINGMVC File Upload implementation + File Upload Tool class design

Source: Internet
Author: User
Tags log log

1. Modify the spring configuration file to add a secondary jar package

        <!--file upload required jar package-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            < artifactid>commons-fileupload</artifactid>
            <version>1.2.1</version>
        </ dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId> commons-io</artifactid>
            <version>1.4</version>
        </dependency>
<!--spring File Upload Form view parser-->
<bean id= "multipartresolver"  class= " Org.springframework.web.multipart.commons.CommonsMultipartResolver ">  
        <property name=" defaultencoding "Value=" UTF-8/>
        <!--upload limit is 200M  --> <property name= "
        maxuploadsize" value= "209715200"/ >
</bean>  

2. Front-end Form form setting: Must set Enctype= "Multipart/form-data"

<form id= "MyForm" name= "MyForm" action= "" method= "Post" enctype= "Multipart/form-data" >

3. Background processing tool class

Package com.group.ssm.utils;
Import Java.io.BufferedInputStream;
Import Java.io.BufferedOutputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.UnsupportedEncodingException;
Import Java.text.DecimalFormat;
Import java.util.ArrayList;
Import Java.util.Date;
Import java.util.List;
Import Java.util.Map;
Import Java.util.Random;

Import Java.util.Set;

Import Javax.servlet.http.HttpServletRequest;
Import Org.apache.commons.fileupload.FileItem;
Import org.apache.commons.fileupload.FileUploadException;
Import Org.apache.commons.fileupload.disk.DiskFileItem;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;
Import Org.apache.commons.fileupload.servlet.ServletFileUpload;
Import Org.apache.commons.lang3.StringUtils;
Import Org.apache.commons.lang3.time.DateFormatUtils;
Import Org.apache.commons.logging.Log;
Import Org.apache.commons.logging.LogFactory;
Import Org.springframework.web.multipart.MultipartFile; Import Org.spriNgframework.web.multipart.MultipartHttpServletRequest;
Import Org.springframework.web.multipart.commons.CommonsMultipartFile; /** * * @date September 6, 2017 * @author lcx * @Description: File Upload processing * * Public class Fileuploadutils {protected final
    Log log = Logfactory.getlog (GetClass ()); private static Long MaxFileSize = 200000000;//default limit is 200M private static String encoding = "utf-8";//Encoding format private



    static List prepaireditems = null; /** * Get File path * * @param filenamewithpath * @return/public static String GetFilePath (Strin
        G Filenamewithpath) {String FilePath = "";
        Filenamewithpath = Filenamewithpath.replace ("/", file.separator);
        int idx = Filenamewithpath.lastindexof (file.separator);
        if (idx!=-1) {FilePath = filenamewithpath.substring (0, IDX);
    return filePath;
   /** * Write content to File * @param context * @param fileName target file * @throws Exception  */public static void WriteFile (String context,string fileName) throws exception{byte[] Bytes=context.getby
        TES ();
        File File=new file (fileName);
        FileOutputStream FOP = new FileOutputStream (file);
        Bufferedoutputstream out = new Bufferedoutputstream (FOP);
        if (!file.exists ()) {file.mkdirs ();
        } out.write (bytes);
        Out.flush ();
    Out.close ();            /** * Copy File * * @param srcfilename * Source files to be copied * @param destfilename *
            Target file * @throws Exception */public static void CopyFile (String srcfilename, String destfilename)
        Throws Exception {bufferedinputstream in = null;
        Bufferedoutputstream out = null;
            try {in = new Bufferedinputstream (new FileInputStream (Srcfilename));
            String destpath = GetFilePath (destFileName); File Pathfile = new file (destpaTH);
            if (!pathfile.exists ()) {pathfile.mkdirs ();
            out = new Bufferedoutputstream (new FileOutputStream) (New File (destFileName));
            int Len;
            Byte[] B = new byte[1024];
            while (len = In.read (b))!=-1) {out.write (b, 0, Len);
        } out.flush ();
            catch (Exception e) {System.out.println ("Copy file failed:" + e.getmessage ());
        Throw e;
            Finally {try {if (in!= null) in.close (); 
            The catch (Exception ex) {} try {if (out!= null) out.close (); The catch (Exception ex) {}}}/** * * @param time document creation * @par 
     AM PersonID Create User ID * @param oldfilename old file name * @return * @throws Exception * return filename * @author LCX * Privatestatic string Getdocpath (Long time,string personid,string oldfilename) throws exception{String affix= ""; if (Stringutils.isnotempty (oldfilename) && oldfilename.lastindexof (".")
        &GT;-1) {affix = Oldfilename.substring (Oldfilename.lastindexof ("."));
    Return to "doc$". Concat (String.valueof (Time)). Concat ("$"). Concat (PersonID). Concat ("$") concat ("Newdoc");
     /** * * @param request * @param resourcepath source file address * @param savepath Save Address * @return * File modified upload Save, if the source file is not empty, then overwrite the source file, if the source file is empty, create a new file * @author LCX * * * @SuppressWarnings ("null") public static Boo
        Lean upload (httpservletrequest request,string resourcepath,string savepath) {bufferedinputstream in = null;

        Bufferedoutputstream out = null;  

        Multiparthttpservletrequest multipartrequest = (multiparthttpservletrequest) request;

        map<string, multipartfile> map = Multipartrequest.getfilemap (); List<MultipartFile> filelist = new arraylist<multipartfile> (); 
        set<string> keys = Map.keyset ();
        for (String Key:keys) {Filelist.add (Map.get (key));
        String Uploadmethod = Request.getparameter ("Uploadmethod");
        if (Savepath = = NULL | | savepath.equals ("")) throw new RuntimeException ("No Save path for file on server");
        File Savepathfile = new file (Savepath); if (!savepathfile.exists ()) {if (!savepathfile.mkdirs ()) throw new RuntimeException ("Create File Upload path
        ("+ Savepath +") failure "); Boolean ismultipart = servletfileupload.ismultipartcontent (Request)//Check whether the form contains files Diskfileitemfactory F
        Ileitemfactory = new Diskfileitemfactory ();
        Fileitemfactory.setsizethreshold (4096);//Set the critical value of the cached temporary file fileitemfactory.setrepository (savepathfile);
        Servletfileupload upload = new Servletfileupload (fileitemfactory);
   upload.setheaderencoding (encoding);     Upload.setsizemax (MaxFileSize);
        List items = null;
        if (prepaireditems!= null) {items = Prepaireditems;
                }else{try {items = (servletfileupload) upload). Parserequest (Request);
                catch (Fileuploadexception e) {e.printstacktrace (); for (int i = 0; i < filelist.size (); i++) {Commonsmultipartfile DFI = (commonsmulti
            Partfile) Filelist.get (i);
            Diskfileitem fi = (Diskfileitem) dfi.getfileitem ();
            String srcfilename = Dfi.getname (). Trim (). ReplaceAll ("\\s*", "");
            try {//output to the file directory Fi.write (new file ("d:\\111\\123" +i+ ". Doc"));
            catch (Exception e) {e.printstacktrace ();
            Long fileSize = Dfi.getsize ();
            Double fitfilesize = 0;
            String filesizestr = ""; DecimalFormat df = new DeCimalformat ("#.00");
                if (double) fileSize > (1024*1024) {fitfilesize = (double) fileSize/(1024*1024);
            Filesizestr = Df.format (fitfilesize) + "M";
                }else{fitfilesize = (double) filesize/1024;
                if (Fitfilesize < 1) Filesizestr = "0" + df.format (fitfilesize) + "KB";
            else Filesizestr = Df.format (fitfilesize) + "KB";
        } System.out.println ("File size is:" +filesizestr);
    return false;
 }

}

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.