Java Web File Upload

Source: Internet
Author: User

One

Java Web File upload requires a few third-party libraries, commonly used by the Apache package, there are two:

Commons-fileupload

Commons-io

Second, the front-end code example:

    <formMethod= "POST"ID= "Uploadapkform"Action= "uploadapk"enctype= "Multipart/form-data">        <P>File:<inputname= "Apkfile"type= "File" /> <!--have multiple properties when multiple files are selected and uploaded simultaneously        </P>        <P>version:<inputname= "Version"type= "text"placeholder= "Please enter version information" />        </P>    </form>
Note:

Enctype= "Multipart/form-data" is a must;

If the input tag of the type= "file" contains the multiple attribute, you can also select multiple file uploads in the pop-up box

Three, backend code example:

        Try {            //determine if the Enctype property is Multipart/form-data            BooleanIsmultipart =servletfileupload.ismultipartcontent (Request); if(!ismultipart) {//not file upload, get data in traditional way//String userId = Request.getparameter ("UserId");                return; }            //to Multipart/form-data            intMaxmemorysize = 1024 * 1000 * 50;//50MB            intMaxrequestsize = 1024 * 1000 * 100;//100MBString Projabsolutepath = Request.getrealpath (""); String Uploadrelativedir= "upload/apk/"; String Uploadtmprelativedir= Uploadrelativedir + "/tmp/"; File Uploaddirobj=NewFile (Projabsolutepath +Uploadrelativedir); if(!uploaddirobj.exists ())            {Uploaddirobj.mkdirs (); } File uploadtmpdirobj=NewFile (Projabsolutepath +Uploadtmprelativedir); if(!uploadtmpdirobj.exists ())            {Uploadtmpdirobj.mkdirs (); }            //Create a factory for disk-based file itemsDiskfileitemfactory factory =Newdiskfileitemfactory (); //when the upload file is too large, because the virtual function uses a limited amount of memory, so at this time to use temporary files to implement the upload file save//This method is to set the critical value (in bytes) of whether to use temporary filesFactory.setsizethreshold (maxmemorysize); //used in conjunction with the previous, set the path to the temporary file (absolute path)factory.setrepository (uploadtmpdirobj); //Create A new file upload handlerServletfileupload upload =Newservletfileupload (Factory); //solve the upload file name in Chinese garbled, tomcat8 do not need//upload.setheaderencoding ("UTF-8"); //Set the size limit (in bytes) of uploaded contentUpload.setsizemax (maxrequestsize); //Parse the requestlist<fileitem> items =upload.parserequest (Request); Iterator<?> iter =Items.iterator (); String FieldName=NULL; Fileitem Item=NULL; String FileName=NULL; String version=NULL;  while(Iter.hasnext ()) {Item=(Fileitem) iter.next (); FieldName=Item.getfieldname (); if(Item.isformfield ()) {//normal form fields, version informationVersion =item.getstring (); System.out.println (FieldName+ " " +version); } Else{//file FieldsFileName =Item.getname (); if(!filename.endswith ("apk")) {//not an apk fileSystem.out.println ("Not apk file"); return; } fileName= Filename.substring (filename.lastindexof ("\ \") + 1); String ContentType=Item.getcontenttype (); BooleanIsInMemory =item.isinmemory (); LongsizeInBytes =item.getsize (); System.out.println (FileName+ "+ ContentType +" "+ IsInMemory +" "+sizeinbytes); Item.write (NewFile (Uploaddirobj, fileName)); }} apkinfomapper.insertversioninfo (version,NewSimpleDateFormat ("Yy-mm-dd HH:mm:ss"). Format (System.currenttimemillis ()), (Uploadrelativedir+fileName)); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }
View Code

Note:

In order to ensure the security of the server, if the file does not provide a download, the upload file should be placed in the outside world can not directly access the directory, such as the Web-inf directory;

Different browsers submit the file name is not the same, some browsers submit the file name is with the path, and some are simply the file name, to process the retrieved file name of the path portion, only the file name part;

To prevent file coverage from occurring, create a unique file name for the upload file

Java Web 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.