Uploading files using the Commons-fileupload component

Source: Internet
Author: User

In a recent project to be useful to commons-fileupload components to implement file Upload function (as a result of useless to the framework), in the use of the process has encountered some problems, after their own pondering also successfully resolved, here to make a record.

 I. Introduction to the Commons-fileupload File upload component

The Commons-fileupload upload component is an open source project for Apache that can be http://commons.apache.org/proper/commons-fileupload/ Download the latest version (this component requires support for the Commons-io package). This component is easy to use, can also realize the upload of one or more files, but also can limit the size of upload files and other functions.

On a file, a file upload request is made up of an ordered list of form items, and FileUpload is able to parse the upload request and then provide a list of individual file table items to the app. Each of these form items implements the Fileitem interface and contains properties such as file names.

  Second, the use of requirements

1. When uploading a file using the Commons-fileupload component, you need to set the Enctype property of the form form to Multipart/form-data, and you need to set the size of the uploaded file in memory, and the extra portion to be stored on the disk.

2. Put the corresponding Commons-fileupload package and Commons-io package copy into your Web project Wen-inf/lib directory and add to Build Path.

 Third, the use of steps

1, first, create the disk factory Diskfileitemfactory object, used to configure the upload component Servletfileupload;

Diskfileitemfactory factory = new diskfileitemfactory ();

Common methods of Diskfileitemfactory class

Method return value Describe
Setsizethrehold () void The method needs to pass in an int parameter to set the maximum memory size (in bytes)
Setrepositorypath ()

void

The method needs to pass in a string parameter to set the temp file directory
Getrepository () File Get Save temporary file address

2. Second, create the Servletfileupload instance, which is the handle to the upload file.

The Servletfileupload object can be constructed from an diskfileitemfactory instance, with the following code:

Servletfileupload upload = Newservletfileupload (factory);

Common methods of Servletfileupload class
Method return value Describe
Ismultipartcontent () Boolean Check if it is a file upload request
Parserequest () List Get all upload domain forms from the Request object

 Iv. Examples of Use (servlet part code)

Here is an example of a simple file upload.

1, the JSP part of the code:

1<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "2pageencoding= "UTF-8"%>3<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >456<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">7<title>file Upload demo</title>89<body>Ten<form action= "/servletpro/fileupload" method= "post" enctype= "Multipart/form-data" > One<table width= "31%" border= "0" align= "center" > A<tr bgcolor= "#CCCCCC" > -<th height= ">" Please select an attachment to upload:</th> -</tr> the<tr> -<td><label> Uploading Files </label><input type= "file" name= "file"/></td> -</tr> -<tr bgcolor= "#CCCCCC" > +&LT;TD height= "><input" type= "Submit" name= "submit" value= "Upload" ></td> -</tr> +</table> A</form> at<% -         if(Request.getattribute ("result")! =NULL) { -Out.println ("<script>alert ('" + request.getattribute ("result") + "');</script>"); -         } -%> -</body> in

2. Create a Uploadfiles folder in the project webcontent/directory to hold the uploaded files.

3. Create a servlet named FileUpload, with the following code:
    

 PackageCom.hyman.servlet; Public classFileUploadextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; PrivateString Uploadfiledir; PrivateServletContext SC;  PublicFileUpload () {Super(); } @Override Public voidInit (servletconfig config)throwsservletexception {Super. init (config); Uploadfiledir= Config.getinitparameter ("Uploaddir"); SC=Config.getservletcontext (); }    protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException { This. DoPost (request, response); }    protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {String simplefilename= ""; String Filedir= Sc.getrealpath ("/") +Uploadfiledir; String message= "File Upload succeeded!" "; if(servletfileupload.ismultipartcontent (Request)) {Diskfileitemfactory Factory=Newdiskfileitemfactory (); Factory.setsizethreshold (20 * 1024);//20KBfactory.setrepository (Factory.getrepository ()); Servletfileupload Upload=Newservletfileupload (Factory); intMaxSize = 2 * 1024 * 1024;//2MBList formlists =NULL; Try{formlists=upload.parserequest (Request); } Catch(fileuploadexception e) {e.printstacktrace (); } Iterator Iterator=Formlists.iterator ();  while(Iterator.hasnext ()) {Fileitem Formitem=(Fileitem) iterator.next (); if(Formitem.isformfield ()) {String fieldname=Formitem.getfieldname (); //This is a form field that is not an upload file and can be formitem.getstring (fieldname) to get the value of the corresponding form field.}Else {                    //Here is the form field where the file is uploadedString name =Formitem.getname (); if(Formitem.getsize () >maxSize) {Message= "The file you uploaded is too large, please re-select No more than 2M files";  Break; } String fileSize=NewLong (Formitem.getsize ()). ToString (); if(Name = =NULL|| "". Equals (name) && "0". Equals (fileSize))Continue; intdelimiter = name.lastindexof ("\ \"); Simplefilename= Delimiter = =-1? Name:name.substring (delimiter + 1); File SaveFile=NewFile (Filedir, simplefilename); Try{formitem.write (saveFile); } Catch(Exception e) {e.printstacktrace (); } }}} request.setattribute ("Result", message); Request.getrequestdispatcher ("Fileupload.jsp"). Forward (request, response); }}

4. Initialize the parameter configuration in Web. xml:

1  <servlet>2     <Description></Description>3     <Display-name>FileUpload</Display-name>4     <Servlet-name>FileUpload</Servlet-name>5     <Servlet-class>Com.hyman.servlet.FileUpload</Servlet-class>6     <Init-param>7         <Param-name>Uploaddir</Param-name>8         <Param-value>Uploadfiles\</Param-value>9     </Init-param>Ten   </servlet> One   <servlet-mapping> A     <Servlet-name>FileUpload</Servlet-name> -     <Url-pattern>/fileupload</Url-pattern> -   </servlet-mapping>

  V. Some problems encountered in the use of the process and solutions

1, each user upload files need to be stored in the user UID through MD5 encryption named folder, that is, you need to create a folder in the Uploadfiles directory and then save the file in the folder.

Can be implemented as follows:

1 String filedir = Sc.getrealpath ("/") + Uploadfiledir; 2 // create a path to a folder 3 String folderName = filedir + "328ae78f9298e9a00c9dfa673280c17d"; 4 New File (folderName); 5 if (! folder.exists ()) {6    folder.mkdir (); 7 }

2, "/" in the path to "\"

Can be used: FolderName = Foldername.replaceall ("/", "\\\\");

The "\" in the path is changed to "/"

Can be used: FolderName = Foldername.replaceall ("\\\\", "/");

3, when uploading the file also submitted a non-uploaded form, the reading of files and other forms of data in the order of the JSP file and the order of the form.

4, in the project, may upload multiple files at the same time, and the full path of these files need to be connected with a specific connector to save to the database. I encountered such a problem in the project, as long as the server restarts, the first time to upload a file save the path set is correct, but after the upload will appear in the path set with the previous upload file path ... This is not the case with the first upload after restarting the server. This problem really tangled for a long time, and later saw on the internet that there might be a problem with the cache Formitem to call the Delete () method to empty the cache, so that after processing still does not solve the problem. I suddenly found myself saving the string object of each upload path set as a member variable of the current servlet!!! The servlet is a singleton, and the servlet is kept in the server as long as it is created by the server, so a string object that holds each upload path set will overlay each uploaded file.

Uploading files using the Commons-fileupload component

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.