Java component FileUpload Upload file implementation code _java

Source: Internet
Author: User

Typically when you are working with a servlet on a form element, the form elements are simple text, and the servlet can easily be processed with request.getparameter (). But when a form contains more than a few simple text, such as uploading a file field, it is still a very complex task for the servlet to parse out each of the httpservletrequest of the compound form directly from the object.
In order to simplify the processing of the "Multipart/form-data" type of data, the corresponding components can be used to deal with it, which can save a lot of coding, support reuse and high efficiency.
For Java components are also some: FileUpload, smartupload and Cos, and so on, this article on the Apache FileUpload explained.

To use FileUpload, you should first download the appropriate components:
1.fileupload software package:http://commons.apache.org/fileupload/
2.io software package:http://commons.apache.org/io/
Unzip the zip package after downloading and copy Commons-fileupload-1.2.1.jar and Commons-io-1.4.jar to Tomcat's webapp/web-inf/lib.

One, Form page (to specify the form's enctype= "Multipart/form-data")--upload.html

 

Two, servlet--uploadservlet to process the form

Package mypack;
Import javax.servlet.*;
Import javax.servlet.http.*;
Import java.io.*;
Import java.util.*;
Import org.apache.commons.fileupload.*;
Import org.apache.commons.fileupload.servlet.*;

Import org.apache.commons.fileupload.disk.*; public class Uploadservlet extends HttpServlet {private string FilePath;//Storing the directory of uploaded files private string TempFilePath;
  The directory of the file is public void init (ServletConfig config) throws servletexception {super.init (config);
  Filepath=config.getinitparameter ("FilePath");
  Tempfilepath=config.getinitparameter ("TempFilePath");
  Filepath=getservletcontext (). Getrealpath (FilePath);
 Tempfilepath=getservletcontext (). Getrealpath (TempFilePath); 
  } public void DoPost (HttpServletRequest request,httpservletresponse response) throws Servletexception, IOException {
  Response.setcontenttype ("Text/plain"); 
  Send response text to client PrintWriter outnet=response.getwriter ();
   try{//Create a Fileitem factory based on HDD diskfileitemfactory factory = new Diskfileitemfactory (); //Set the size of the buffer used to write data to the hard disk, 4K factory.setsizethreshold (4*1024);

   Sets the temporary directory Factory.setrepository (new File (TempFilePath));
   Create a file upload processor servletfileupload upload = new Servletfileupload (factory); 
  
   Set the maximum size of the file that is allowed to be uploaded, 4M upload.setsizemax (4*1024*1024);  

   List * * Fileitem/items = upload.parserequest (request);
   Iterator iter = Items.iterator ();
    while (Iter.hasnext ()) {Fileitem item = (Fileitem) iter.next (); if (Item.isformfield ()) {Processformfield (item,outnet);//Handle ordinary form fields}else{Processuploadedfile (item,outnet);
  Process upload File}} outnet.close ();
  }catch (Exception e) {throw new Servletexception (e);
  } private void Processformfield (Fileitem Item,printwriter outnet) {String name = Item.getfieldname ();
  String value = item.getstring ();
 Outnet.println (name+ ":" +value+ "/r/n"); private void Processuploadedfile (Fileitem Item,printwriter outnet) throws exception{String Filename=item.getname (
  ); int Index=filename. LastIndexOf ("//");
  Filename=filename.substring (Index+1,filename.length ());
  
  Long Filesize=item.getsize ();

  if (Filename.equals ("") && filesize==0) return;
  File UploadedFile = new file (filepath+ "/" +filename);
  Item.write (UploadedFile);
  Outnet.println (filename+ "is saved.");
 Outnet.println ("The size of" +filename+ "is" +filesize+ "/r/n");
 }
}

The servlet is configured in Web.xml as:

<servlet>
  <servlet-name>upload</servlet-name>
  <servlet-class>mypack. uploadservlet</servlet-class>
  <init-param>
   <param-name>filePath</param-name>
   <param-value>store</param-value>
  </init-param>
  <init-param>
   < param-name>tempfilepath</param-name>
   <param-value>temp</param-value>
  </ init-param>

 </servlet>

 <servlet-mapping>
  <servlet-name>upload</ servlet-name>
  <url-pattern>/upload</url-pattern>
 </servlet-mapping>

To this has completed a simple upload file function-access to the form page, select files and then click the upload file. If you want to upload files to the server at the same time, but also save the file to the database, you can get to the file name, save the file name in the database, so that the file can be based on the filename of the user's files to choose out!

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.