Example of form-based file upload in java

Source: Internet
Author: User
Tags character set constructor file upload tomcat

If the form element <input type = "file"/> is used in the form, the browser automatically generates an input box and a button when parsing the form, the input box allows you to enter the name and path of the local file. You can click the button to open a file selection box for the browser to select a file:

When a form needs to upload a file, you must specify the value of form enctype as multipart/form-data.

In the form element syntax, the enctype attribute specifies the encoding type used by the browser when data is sent to the server.

Enctype attribute values:

Application/x-www-form-urlencoded: default value of the form enctype attribute. This encoding scheme uses a limited character set. When a non-letter or number is used, it must be replaced by "% HH" (H represents a hexadecimal number ). This encoding cannot meet requirements for large-capacity binary data or text containing non-ASCII characters.

Multipart/form-data: form sets the enctype = "multipart/form-data" attribute to indicate that the form transmits data in binary format.

Commons-basic principles of fileupload component Upload

The FileUpload component treats all elements submitted by the page (common form fields, such as text and file fields) as the same FileItem, in this way, the request submitted on the upload page is an ordered combination of FileItem. The FileUpload component can parse the request and return a FileItem. For each FileItem, the FileUpload component can determine whether it is a common form field or a file field, so that different operations can be taken based on different types-if it is a form field, read the value. If it is a file field, save the file to the server hard disk or memory.

Commons-fileupload component API

ServletFileUpload processes the uploaded file data and encapsulates each part of the data into a FileItem object.

DiskFileItemFactory is the factory for creating FileItem objects. In this factory class, you can configure the memory buffer size and Directory for storing temporary files.

When ServletFileUpload receives the uploaded file data, it will save the content to the memory cache. If the file content exceeds the buffer size specified by DiskFileItemFactory, the file will be saved to the disk, stored as temporary files in the directory specified by DiskFileItemFactory. After all the file data is received, ServletUpload writes the data from the file to the file under the Upload file directory.

Perform the following operations to upload and download files:

First, load the necessary jar packages: commons-fileupload-1.2.1.jar, commons-io-1.4.jar"

Steps:

0. Create the object of the FileItemFactory subclass DiskFileItemFactory

1. To obtain the ServletFileUpload object, first obtain an object of FileItemFactory, and then call new ServletFileUpload (FileItemFactory fif); method to obtain the ServletFileUpload object

2. To obtain the FileItem set, first obtain the ServletFileUpload object, and then call the parseRequest () method of the object to obtain the List of fileitems.

3. Obtain the FileItem set from the HttpServletRequest object.

4. Traverse the above set: determine whether it is a form field or a file field

The following is a sample code for file upload operations.

// 1. Verify whether the FileUpload component is used
Boolean isMultipart = ServletFileUpload. isMultipartContent (request );
 
       
 
// 2.1 not used
 
If (! IsMultipart ){
 
Response. getWriter (). println ("no file domain ");
 
Return;
 
        }
 
       
 
// 2.2
 
       
 
// 3. Get the DiskFileItemFactory object
 
DiskFileItemFactory itemFactory = new DiskFileItemFactory ();
 
       
 
// 4. Get the ServletFileUpload object
 
ServletFileUpload fileUpload = new ServletFileUpload ();
 
FileUpload. setFileItemFactory (itemFactory );
 
Set the maximum size of the uploaded file
 
FileUpload. setFileSizeMax (1000*100 );
 
       
 
String forwardPage = null;
 
       
 
Try {
 
// 5. Call the parseRequest () method of ServletFileUpload to obtain the set of fileitems
 
List <FileItem> items = fileUpload. parseRequest (request );
 
           
 
Map <String, String> paramMap = new HashMap <String, String> ();
 
FileItem fileItem = null;
 
           
 
// 6. Traverse the set obtained in step 5
 
Iterator <FileItem> it = items. iterator ();
 
While (it. hasNext ()){
 
FileItem item = it. next ();
 
// 7. Verify whether it is a form field
 
If (item. isFormField ()){
 
// 7.1 is a form field. Put the fieldName and value of the obtained form field in map.
 
Obtain the field name of the field in the form.
 
String fieldName = item. getFieldName ();
 
Obtain the field value corresponding to the above field name in the form.
 
String value = item. getString ("UTF-8 ");
 
                   
 
ParamMap. put (fieldName, value );
 
                }
 
// 7.2 is not a form field, that is, a file field. Get the FileItem object. Pay attention to the restrictions.
 
Else {
 
The FileItem object corresponding to the file is obtained here.
 
FileItem = item;
 
                }
 
                   
 
            }
 
           
 
// 8. Upload a file to the FileItem object obtained in 7.2.
 
// 10.1 obtain the full path name
 
String path = null;
 
           
 
Path = this. getServletContext (). getRealPath ("/photoes ");
 
           
 
File photoesDir = new File (path );
 
If (! PhotoesDir. exists ()){
 
PhotoesDir. mkdir ();
 
            }
 
           
 
Path = path + "/" + paramMap. get ("username ");
 
           
 
File file = new File (path + ". jpg ");
 
           
 
// 10.2 Upload operation to save the files uploaded on the page to the server
 
FileItem. write (file );
Two preparations for uploading File forms

1. Change the submission method to POST.

2. Change the value of the enctype attribute to multipart/form-data.

When obtaining the form value

1. The request. getParameter () method cannot be used, because this method can only obtain strings and does not support binary.

2. Use the fileUpload component to read the uploaded file and form field.

Core idea of fileUpload component

The fileUpload component considers that all form fields (including file fields and text fields) are FileItem objects.

Steps:

1. Get a List composed of FileItem objects

2. Traverse the List

3. Determine whether a FileItem object is a form field or a file field for different processing.

Detailed steps:

1. Check whether the form's enctype is multipart/form-data to determine whether to use the FileUpload component for parsing requests.

2. If the form's enctype is multipart/form-data, you need to obtain the List: List <FileItem> list = null of the corresponding FileItem object encapsulated in all form fields;

3) obtain the ServletFileUpload object and call the public java. util. List parseRequest (javax. servlet. http. HttpServletRequest request) of the object)

Method to obtain the List of encapsulated fileitems

2) you need to use the ServletFileUpload constructor to create the ServletFileUpload object:

^ Use any constructor to obtain the ServletFileUpload object, but you must first obtain the FileItemFactory object.

* ServletFileUpload upload = new ServletFileUpload ();

Upload. setFileItemFactory (factory );

* ServletFileUpload upload = new ServletFileUpload (factory );

1) the FileItemFactory interface is used to create a class object: DiskFileItemFactory.

3. You can call DiskFileItemFactory to optimize file upload:

1) setSizeThreshold (int sizeThreshold): set the size of the temporary folder.

2) setRepository (): set a temporary folder

4. You can call the ServletUpload method to control file upload.

1) setFileSizeMax: sets the maximum Upload value for a single file.

2) setSizeMax: sets the maximum value of the total uploaded files, in bytes.

5. Chinese garbled text:

1) before parsing the request: request. setCharacterEncoding ("UTF-8 & Prime;); can solve the file domain garbled problem

2) when parsing form fields, use: new String (value. getBytes ("ISO-8859-1 & Prime;)," UTF-8 & Prime;); to solve Chinese garbled problem.

But sometimes, even if we set it as above, we can still garbled characters in Chinese. At this time, most of the problem lies in the tomcat configuration and open the tomcat service. xml file. Pay attention to the following section.

<Connector port = "8989 & Prime; protocol =" HTTP/1.1 & Prime;

ConnectionTimeout = "20000 & Prime;

RedirectPort = "8443 & Prime; useBodyEncodingForURI =" true "/>

You can configure EncodingUrl in the program only when the red part is added.

The following code is related to object downloading.

// 1. Set the response header contentType: application/x-msdownload->

// Tell the browser that the type of content output is not a common text file or HTML file, but a download file to be saved locally

// Response. setHeader ("conent-type", "application/x-msdownload ");

Response. setContentType ("application/x-msdownload ");

// 2. Set the response header Content-Disposition: attachment->

// The Web server does not want the browser to directly process the corresponding entity content. Instead, the user selects to save the corresponding entity content to a file.

Response. setHeader ("Content-Disposition", "attachment; filename=hahaha.ppt ");

// 3. Use response. getOutputStream () for io operations

OutputStream OS = response. getOutputStream ();

BufferedOutputStream bos = new BufferedOutputStream (OS );

// File input stream

InputStream is = null;

Is = new FileInputStream ("E: source90515javaeefileuploadfileUpload.ppt ");

BufferedInputStream bis = new BufferedInputStream (is );

Int length = 0;

Byte [] temp = new byte [1*1024*10];

While (length = bis. read (temp ))! =-1 ){

Bos. write (temp, 0, length );

System. out. println ("loop operation ...");

}

Bis. close ();

Bos. close ();

However, the above method cannot be downloaded by download tools such as thunder. If you want to download things such as thunder, you can simply write it like this.

Request. getRequestDispatcher ("/data/fileUpload.ppt ")

. Forward (request, response );

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.