File Upload (Java web)

Source: Internet
Author: User

File Upload:

Requirements for the form:

* method= "POST"
* enctype= "Multipart/form-data"
* You need to add a file form item to the form: <input type= "file" name= "xxx"/>

Requirements for Servlets:

* Request.getparametere ("xxx"); This method always returns NULL when the form is Enctype= "Multipart/form-data".
* ServletInputStream Request.getinputstream (); the body containing the entire request!

steps for uploading files (First you need to guide the package--Commons-fileupload.jar and Commons-io.jar):

1. Create factory: Diskfileitemfactory factory = new Diskfileitemfactory ();

2. Create parser: Servletfileupload SFU = new Servletfileupload (factory);

3. Use parser to parse request, get Fileitem set:list<fileitem> fileitemlist = sfu.parserequest (request);

Related Methods of Fileitem:

* Boolean Isformfield (): Whether it is a normal form item! Returns true for normal form items if False is the file form item!
* String getfieldname (): Returns the name of the current form item;
* String getString (String charset): Returns the value of the table item;
* String getName (): Returns the uploaded file name
* Long GetSize (): Returns the number of bytes uploaded to the file
* InputStream getInputStream (): Returns the input stream corresponding to the uploaded file
* Void Write (file destfile): Saves the contents of uploaded files to the specified file.

Code implementation in the servlet in the upload file (V1.0):

1Request.setcharacterencoding ("Utf-8");2Response.setcontenttype ("Text/html;charset=utf-8");3         4         /**5 * File upload 3 steps away6 * 1. Create a factory7 * 2. Create a parser8 * 3. Use parser to parse request, get Fileitem collection9          */Ten          One         //Create a factory ADiskfileitemfactory factory =Newdiskfileitemfactory (); -         //Creating a parser -Servletfileupload SFU =Newservletfileupload (factory); the          -         //Get Fileitem Collection -         Try { -list<fileitem> list =sfu.parserequest (request); +              -Fileitem fi1 = list.get (0); +Fileitem Fi2 = list.get (1); AString FileName =fi2.getname (); atSystem.out.println ("Name:" +fi2.getname ()); -System.out.println ("Size:" +fi2.getsize ()); -              -File DestFile =NewFile ("D://demo", fileName);//Set Storage location -             Try { - Fi2.write (destfile); in}Catch(Exception e) { -                 //TODO auto-generated Catch block to e.printstacktrace (); +             } -}Catch(fileuploadexception e) { the e.printstacktrace (); *}

Issues to note in file uploads:

1. The file must be saved to Web-inf!
* Purpose is to not allow the browser to directly access the

2. File name Related issues
* Some browsers upload filenames that are absolute paths, which require cutting! C:\files\xxx.jpg
String filename = fi2.getname ();
int index = filename.lastindexof ("\ \");  //test whether you need to cut
if (index! =-1) { 
filename = filename.substring (index+1);
}
* File name garbled or normal table item garbled: request.setcharacterencoding ("Utf-8"), because FileUpload inside will call Request.getcharacterencoding ();
> Request.setcharacterencoding ("Utf-8");//Priority Low
> Servletfileupload.setheaderencoding ("Utf-8");// High priority
* file with the same name, we need to add a prefix to each file, which is guaranteed to not be duplicated. UUID

3. Directory break down
* Multiple files cannot be stored in one directory.
> First character break: Use the first letter of the file as the directory name, for example: Abc.txt, then we save the file to a directory. If the A directory does not exist at this time, then create it.
> Time Break: Use the current date as a table of contents.
> Hash Break:
* Get int value by file name, call Hashcode ()
* It int value to 16 binary 0~9, a~f
* Get 16 binary top two to generate directory, directory two layer! For example: 1b2c3d4e5f,/1/b/Save the file.


4. Size limit for uploaded files
* Single File size limit
> Sfu.setfilesizemax (100*1024): Limit single file size to 100KB
> The above method call must be called before parsing begins!
> If the uploaded file exceeds the limit, an exception will be thrown when the Parserequest () method executes! Fileuploadbase.filesizelimitexceededexception
* Entire request all data size limit
> Sfu.setsizemax (1024 * 1024);//Limit the entire form size to 1M
> This method must also be called before the Parserequest () method
> If the uploaded file exceeds the limit, an exception will be thrown when the Parserequest () method executes! Fileuploadbase.sizelimitexceededexception


5. Cache size and Temp directory
* Cache Size: How big it is before you save it to your hard drive! Default is 10KB
* Temp directory: What directory is saved to the hard disk
Set cache size with temp directory: New Diskfileitemfactory (20*1024, New File ("F:/temp"))//cache is 20KB, temporary directory is f:/temp

File Upload (Java web)

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.