Upload using the Apache-commons-fileupload component.

Source: Internet
Author: User
Tags http file upload
Commons is a Java sub-project in the Apache open source code organization. This project mainly involves some common modules, such as file upload, command line processing, database connection pool, and xml configuration file processing. These projects bring together the painstaking efforts of software engineers from all over the world, and their performance and stability have all stood the test of practical applications. Effective use of these projects will bring obvious effects to the development. Fileupload is a sub-project used to process HTTP file uploads. This article describes how to use fileupload to process the file information submitted to the server by the browser.

To enable the developer who first came into contact with fileupload to better understand the project, we will implement a simple file upload function and introduce the development steps and detailed code step by step.

  Environment preparation

1. Download and install Tomcat (there are many articles about tomcat installation and usage, which will not be introduced here );

2. Download the jar package commons-fileupload-1.0-beta-1.jar for file upload and copy the file to the {$ Tomcat}/common/lib directory (where {$ Tomcat} is the tomcat installation directory );

3. because the fileupload sub-project also needs to use another project commons-beanutils, you must download beanutils and copy the extracted file commons-beanutils.jar to the {$ Tomcat}/common/lib directory.

  Development file upload page

The file upload interface 1 is shown. To increase efficiency, we designed three file domains and uploaded three files at the same time.

Figure 1 file upload page

The HTML code of the page is as follows:

     
      
<HTML>
      
<Head>
<Title> File Upload demonstration </title>
</Head>
<Body bgcolor = "# ffffff" text = "#000000" leftmargin = "0" topmargin = "40" marginwidth = "0" marginheight = "0">
<Center>
<H1> File Upload demonstration <Form name = "uploadform" method = "Post" Action = "Save. jsp" enctype = "multipart/form-Data">
<Table border = "1" width = "450" cellpadding = "4" cellspacing = "2" bordercolor = "# 9bd7ff">
<Tr> <TD width = "100%" colspan = "2">
File 1: <input name = "file1" size = "40" type = "file">
</TD> </tr>
<Tr> <TD width = "100%" colspan = "2">
File 2: <input name = "file2" size = "40" type = "file">
</TD> </tr>
<Tr> <TD width = "100%" colspan = "2">
File 3: <input name = "file3" size = "40" type = "file">
</TD> </tr>
</Table>
<Br/>
<Table>
<Tr> <TD align = "center"> <input name = "Upload" type = "Submit" value = "Start upload"/> </TD> </tr>
</Table>
</Form>
</Center>
</Body>
</Html>

In the code, pay special attention to the black body. Make sure that the value of the form's enctype is multipart/form-data, so that the browser can correctly upload files.

  Process uploaded file information

This document describes how to use commons-fileupload. To facilitate modification and debugging, a JSP file is used for processing the storage of uploaded files. We save all files uploaded by the browser in a specified directory and display the details of all uploaded files on the page. The result of saving the page is shown in figure 2.

Figure 2 save page

Let's take a look at the save. JSP code:

     
      
<%
      
/**
* Demonstrate how to upload files
* @ Author <a href = "mailto: winter.lau@163.com"> Winter Lau </a>
* @ Version $ ID: Save. jsp, v 1.00 10:10:15
*/
%>
<% @ Page Language = "Java" contenttype = "text/html; charset = GBK" %>
<% @ Page import = "Java. util. *" %>
<% @ Page import = "org. Apache. commons. fileupload. *" %>
<HTML>
<Head>
<Title> Save the uploaded file </title>
</Head>
<%
String MSG = "";
Fileupload Fu = new fileupload ();
// Set the size of the file to be uploaded. Unit: bytes.
Fu. setsizemax (10000000 );
// Maximum size that will be stored in memory?
// Set up to only data that can be stored in the memory, in bytes
Fu. setsizethreshold (4096 );
// Set the data stored in the hard disk directory when the file size exceeds the value of getsizethreshold ()
Fu. setrepositorypath ("C: // Temp ");
// Start reading upload information
List fileitems = Fu. parserequest (request );
%>
<Body bgcolor = "# ffffff" text = "#000000" leftmargin = "0" topmargin = "40" marginwidth = "0" marginheight = "0">
<Font size = "6" color = "blue"> file list: </font>
<Center>
<Table cellpadding = 0 cellspacing = 1 border = 1 width = "100%">
<Tr>
<TD bgcolor = "#008080"> file name </TD>
<TD bgcolor = "#008080"> size </TD>
</Tr>
<%
// Process each uploaded file in sequence
Iterator iter = fileitems. iterator ();
While (ITER. hasnext ()){
Fileitem item = (fileitem) ITER. Next ();
// Ignore all other forms that are not in the file Field
If (! Item. isformfield ()){
String name = item. getname ();
Long size = item. getsize ();
If (name = NULL | Name. Equals ("") & size = 0)
Continue;
%>
<Tr>
<TD> <% = item. getname () %> </TD>
<TD> <% = item. getsize () %> </TD>
</Tr>
<%
// Save the uploaded file to the specified directory
Name = Name. Replace (':','_');
Name = Name. Replace ('//','_');
Item. Write ("F: //" + name );
}
}
%>
</Table>

<Br/>
<A href00000000upload.html "> return to the upload page </a>
</Center>
</Body>
</Html>

Note the significance of some parameter values of the fileupload object in this file. The following code shows the three parameters sizemax, sizethreshold, and repositorypath:

     
      
Fileupload Fu = new fileupload ();
      
// Set the size of the file to be uploaded. Unit: bytes.
Fu. setsizemax (10000000 );
// Maximum size that will be stored in memory?
// Set up to only data that can be stored in the memory, in bytes
Fu. setsizethreshold (4096 );
// Set the data stored in the hard disk directory when the file size exceeds the value of getsizethreshold ()
Fu. setrepositorypath ("C: // Temp ");

The meanings of these three parameters are as follows:

Sizemax is used to set the maximum size of the uploaded file. Once the size of the uploaded file exceeds this value, a fileuploadexception is thrown, prompting that the file is too large;

Sizethreshold sets the buffer size in the memory. Once the file size exceeds this value, the program automatically stores other data in the directory specified by repositorypath as a buffer. Setting the value of this parameter can ensure stable and efficient operation of the server;

Repositorypath specifies the buffer directory.

  Precautions

According to the actual application results, this module can work stably and efficiently. The value of the sizethreshold parameter is crucial. If the setting is too large, it will occupy too much memory. If the setting is too small, the hard disk will be frequently used as a buffer to sacrifice performance. Therefore, this value must be set based on the size distribution of uploaded files. For example, if the size of most files is around kb, you can use kb as the value of this parameter. Of course, it is not appropriate to increase the size. The use of commons-fileupload to process HTTP File Upload is very small, but there are many things worth studying.

 

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.