Java File Upload

Source: Internet
Author: User

1.pom.xml Baidu

2. Core:

2.1 Entity Class Fileuploaddatabucket:

 PackageCom.dzpykj.files;ImportJava.io.File;/*** Upload a bucket of file staging data *@authorChaixy*/ Public classFileuploaddatabucket {/**the file to be saved*/     PublicFile Desfile; /**source File*/     PublicFile srcfile; /**source file name (with suffix)*/     PublicString Srcfilename; /**name of the stored file (with suffix)*/     PublicString Desfilename; /**File Type*/     PublicString Suffixname; /**Base Path*/     PublicString BasePath; /**storing files for different functions may have different folders, or different file types of the same module to have different folders, will create a new folder under the underlying path, which is used to store the path after the base path*/     PublicString Ownpath; /**Storage paths for data stores*/     PublicString Dbfilepath; /**File Size*/     PublicString fileSize; /**file MD5*/     PublicString contentMD5;  PublicFile Getdesfile () {returnDesfile; }     Public voidsetdesfile (File desfile) { This. Desfile =Desfile; }     PublicFile Getsrcfile () {returnSrcfile; }     Public voidsetsrcfile (File srcfile) { This. Srcfile =Srcfile; }     PublicString Getsrcfilename () {returnSrcfilename; }     Public voidsetsrcfilename (String srcfilename) { This. Srcfilename =Srcfilename; }     PublicString Getdesfilename () {returnDesfilename; }     Public voidsetdesfilename (String desfilename) { This. Desfilename =Desfilename; }     PublicString Getsuffixname () {returnSuffixname; }     Public voidsetsuffixname (String suffixname) { This. Suffixname =Suffixname; }     PublicString Getbasepath () {returnBasePath; }     Public voidSetbasepath (String basepath) { This. BasePath =BasePath; }     PublicString Getownpath () {returnOwnpath; }     Public voidSetownpath (String ownpath) { This. Ownpath =Ownpath; }     PublicString Getdbfilepath () {returnDbfilepath; }     Public voidSetdbfilepath (String dbfilepath) { This. Dbfilepath =Dbfilepath; }     PublicString GetFileSize () {returnfileSize; }     Public voidsetfilesize (String fileSize) { This. fileSize =fileSize; }     PublicString getContentMD5 () {returncontentMD5; }     Public voidsetContentMD5 (String contentMD5) { This. contentMD5 =contentMD5; }    }

2.2 Upload File Tool class Fileuploadutils:

 PackageCom.dzpykj.files;ImportJava.io.File;Importjava.io.IOException;ImportJava.math.BigDecimal;ImportJava.text.SimpleDateFormat;Importjava.util.ArrayList;Importjava.util.Date;ImportJava.util.Iterator;Importjava.util.List;ImportJava.util.Random;Importjavax.servlet.http.HttpServletRequest;Importorg.apache.commons.codec.digest.DigestUtils;Importorg.apache.commons.lang3.StringUtils;ImportOrg.springframework.web.multipart.MultipartFile;Importorg.springframework.web.multipart.MultipartHttpServletRequest;ImportOrg.springframework.web.multipart.commons.CommonsMultipartResolver;/*** File Upload *@authorChaixy*/ Public classFileuploadutils {/*** Upload files and return Data bins (store data to be saved to the database) *@paramRequest *@parambasepath Base Path (do not carry delimiters and separators, tool classes will be automatically complete) *@paramOwnpath for different functions of the file may have different folders, or different file types of the same module to have a different folder, will be in the base path to create a new folder, this field for the base path after the respective path (do not carry the delimiter, the tool class will automatically complete) * @returnData Bucket*/     Public StaticList<fileuploaddatabucket> Uploadfiles (httpservletrequest request, String BasePath, String ownpath)throwsIOException {//Create a general-purpose multi-part parserCommonsmultipartresolver Multipartresolver =NewCommonsmultipartresolver (Request.getsession (). Getservletcontext ()); List<FileUploadDataBucket> databuckets =NewArraylist<>(); //determine if request has a file upload, that is, multipart requests        if(Multipartresolver.ismultipart (Request)) {//convert to multi-part RequestMultiparthttpservletrequest multirequest =(multiparthttpservletrequest) request; //get all the file names in RequestIterator<string> iter =Multirequest.getfilenames ();  while(Iter.hasnext ()) {List<MultipartFile> Multipartfiles =Multirequest.getfiles (Iter.next ());  for(Multipartfile multipartfile:multipartfiles) {String srcfilename= Multipartfile.getoriginalfilename ();//original name with suffixString suffixname = srcfilename.substring (Srcfilename.lastindexof (".") + 1);//File TypeString contentMD5 =Digestutils.md5hex (Multipartfile.getbytes ()); DoubleSize = (multipartfile.getsize () * 1.0)/(1024 * 1.0)/(1024 * 1.0); BigDecimal BG=NewBigDecimal (size); DoubleF1 = Bg.setscale (2, bigdecimal.round_half_up). Doublevalue (); String fileSize= F1 + ""; String Desfilename= Generatefilename () + "." +Suffixname; String Dbfilepath= Ownpath + File.separator +Desfilename; String Desfilepath= BasePath + File.separator +Dbfilepath; File Desfile=NewFile (Desfilepath); if(!desfile.exists ())                    {Desfile.mkdirs (); }                                        if(Stringutils.isnotblank (srcfilename)) {Multipartfile.transferto (desfile); Fileuploaddatabucket Fudb=NewFileuploaddatabucket ();                        Fudb.setbasepath (BasePath);                        FUDB.SETCONTENTMD5 (CONTENTMD5);                        Fudb.setdbfilepath (Dbfilepath);                        Fudb.setdesfile (Desfile);                        Fudb.setdesfilename (Desfilename);                        Fudb.setfilesize (fileSize);                        Fudb.setownpath (Ownpath);                        Fudb.setsrcfilename (Srcfilename);                        Fudb.setsuffixname (Suffixname);                    Databuckets.add (FUDB); }                }            }        }        returndatabuckets; }        Private Staticstring Generatefilename () {string Datestr=NewSimpleDateFormat ("Yyyymmddhhmmss"). Format (NewDate ()); LongTimemillis =System.currenttimemillis (); intRandom =NewRandom (). Nextint (90) +10; returndatestr+timemillis+Random; }}

2.3 Configuration Files

    class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" >        <property name= " Maxuploadsize ">            <value>104857600</value>        </property>        <property name=" Maxinmemorysize ">            <value>4096</value>        </property>        <property name=" Defaultencoding ">            <value>utf-8</value>        </property>        <!--<property name= "Defaultencoding" value= "UTF-8"/>-    </bean>

3. Simple test

3.1Controller Layer Fileuploadtestcontroller:

 PackageCom.dzpykj.files.upload;Importjava.io.IOException;Importjava.util.List;Importjavax.servlet.http.HttpServletRequest;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.ResponseBody;ImportCom.dzpykj.files.FileUploadDataBucket;Importcom.dzpykj.files.FileUploadUtils;Importcom.fasterxml.jackson.databind.ObjectMapper; @Controller Public classFileuploadtestcontroller {@RequestMapping ("/fileupload") @ResponseBody PublicString upload (httpservletrequest req)throwsioexception{List<FileUploadDataBucket> databuckets = fileuploadutils.uploadfiles (req, "E:\\fiels", "pic"); String Jsonstr=Newobjectmapper (). writevalueasstring (Databuckets). toString ();        System.out.println (JSONSTR); returnJsonstr; }    }

3.2 Simple JSP page fileupload.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" >

Java File Upload

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.