Using Apache Commons-fileupload.jar to implement file uploads

Source: Internet
Author: User
Tags file size html form save file

Reprint from: http://hi.baidu.com/ljzcome/blog/item/b33c38908d696b88a977a4c9.html

Use Apache Commons-fileupload.jar implementation file upload 2008-04-18 01:09

Reference address: Http://commons.apache.org/fileupload

Use FileUpload

Depending on your application requirements, FileUpload can be used in many different ways. In the simplest case, you can call an easy way to parse the servlet request and then process the form list as they are submitted to your application. On other terminals, you may also decide to customize the FileUpload to fully control how individual tables are stored. For example, you might want to stream content to the data.
here. We will describe the basic usage of fileupload, and then explain some of the simpler and most commonly used patterns. The personalization of FileUpload is described here.

How it works

A file upload request consists of a list of ordered table items that are encoded according to RFC1867 and are based on the form's file upload in HTML. FileUpload can parse such a request and provide a list of individual upload form items to your application. Each of these form items implements the Fileitem interface without having to consider how it is potentially implemented. Each file's form item has a series of properties that may be useful to your application, for example, each item has a name and file type, and you can provide a inputstream to fetch its data. On the other hand, you might want to deal with these options differently, depending on whether the data comes from a normal text box or a simple HTML form field, or a file that can be uploaded, based on a list item that is not a rule for this option. The Fileitem interface provides a variety of ways to determine whether it is an uploaded file, and then you can process the data in the most appropriate way. FileUpload uses Fileitemfactory to create a new file project. That's why it gives fileupload flexibility. The factory ultimately controls the creation of each project. The default factory stores data for the project in memory or on disk, depending on the size of the project (for example, byte data). Of course, this action can be customized to meet the needs of your application.

Resolution requests

before you can handle the options you want to upload, it's obvious that you need to parse the requests themselves first. It's straightforward to make sure that the request is not a file to upload, but FileUpload makes it simpler, and you just provide a static way to do it.

Check if it is a file upload request
Boolean ismultipart = fileupload.ismultipartcontent (request);

Now we are ready to parse this request to an alternative option. The result of parsing is a list of file options, each of which implements the Fileitem interface, and processing these options is discussed below.

The simplest case

The simplest use scenario can refer to the following: The uploaded option must reside in memory at a modest size; the larger file upload option must be written to the temporary file on the disk; the large file upload request must not be allowed; The default memory-resident option maximum size, the maximum allowable upload file request, And the storage of temporary files is acceptable;

It is not easy to handle such a request in this scenario:

Create a new file upload handle
Diskfileupload upload = new Diskfileupload ();
Parsing requests
List * * Fileitem/items = upload.parserequest (request);

That's all we need to do, really.
The result of parsing is a list of file items, each of which implements the Fileitem interface. The processing of these items is discussed below.

Practise more control.

If your scenario is very close to the simplest way to use, as you can see in the above, but you need more control over the critical size and temporary file hosting address, you can use the Diskfileupload class method to customize these actions, like this:

Create a new file upload handle
Diskfileupload upload = new Diskfileupload ();
Set Upload Parameters
Upload.setsizethrehold (maximum memory size);
Upload.setsizemax (maximum request size);
Upload.setrepositorypath (temporary catalogue);
Parsing requests
List * * Fileitem/items = upload.parserequest (request);

Of course, each configuration method is independent of the others, but if you want to configure them at once, you can use the optional Parserequest () method, like this:

Create a new file upload handle
Diskfileupload upload = new Diskfileupload ();
Parsing requests
List * * Fileitem/items = upload.parserequest (Request,
Memory size, allowed to upload the maximum file, temporary directory);

If you want to more control the parsing of requests, such as storing the upload options somewhere else, for example, in a database-you can refer to the custom fileupload.

Processing Upload Options

Once the parsing process is complete, you can obtain a list of file options for further processing. In most cases, you will be able to handle file uploads differently depending on the form field of the rule. So you might deal with it in this way:

Options for handling uploads
Iterator iter = Items.iterator ();
while (Iter.hasnext ()) {
Fileitem item = (Fileitem) iter.next ();

if (Item.isformfield ()) {
Processformfield (item);
} else {
Processuploadedfile (item);
}
}

For a regular form field, you might be interested in only its name and its string value. You will also think that it is simple to deal with them:

Working with a Rule form field
if (Item.isformfield ()) {
String name = Item.getfieldname ();
String value = item.getstring ();
...
}

And for an upload of a file, there are a lot of different things you want to know before you can handle it, and here's an example of a method that you might be interested in.

Process a file Upload
if (!item.isformfield ()) {
String fieldName = Item.getfieldname ();
String fileName = Item.getname ();
String ContentType = Item.getcontenttype ();
Boolean isinmemory = Item.isinmemory ();
Long sizeinbytes = Item.getsize ();
...
}

For these uploaded files, you generally do not want to access them through memory, unless they are small, or you do not have any other good method, further, you want to treat the content as a file flow, or the entire file to the final address. FileUpload provides a simple way to do these things.

Handling a file upload situation
if (WriteToFile) {
File UploadedFile = new file (...);
Item.write (UploadedFile);
} else {
InputStream Uploadedstream = Item.getinputstream ();
...
Uploadedstream.close ();
}

Note that in the default FileUpload implementation, the Write () method attempts to rename the file to a specific location, if the data is already in the temporary file, and if the rename fails, the actual copy file is completed (. For other reasons, or the data is already in memory. If you do need to take the uploaded data in memory, you simply call the Get () method to obtain it as an array of characters.


Process an uploaded file in memory
byte[] data = Item.get ();
...

Interaction with antivirus software when the Web container is running, while antivirus software runs on the same system at the same time, the use of fileupload in applications can lead to unpredictable things. This section will describe some of the situations you might encounter, and we will provide some ways to deal with them. The default FileUpload implementation will write options that exceed its upload size in memory to disk. When such a file is closed, the antivirus software in any system wakes up and checks it, potentially isolating the file-that is, moving it to a specific place that does not cause problems. This, of course, is an accident for developers, as the files just uploaded will not be processed. On the other hand, those uploaded files that are smaller than the set memory size will be kept in memory, this will not be detected by antivirus software, so it is possible that the virus resides in a system in some way (although, if it is written to disk, antivirus software locates and detects it). A common solution is to set up a directory specifically in the system to store the uploaded files, and then configure the antivirus software to ignore the directory. This will ensure that uploaded files are not quarantined in the system, but this gives the application developer the responsibility to scan the virus. The task of scanning these uploaded files can be implemented in external processing. This allows you to move clean files to an "improved" location, or you can integrate antivirus into your application. As for how to scan an external processing or integration virus into a
Application, this is beyond the scope of this document. What's next?

I hope this page will provide you with a good opinion, so that you can use FileUpload in your own application. For more on the methods described here, and other available methods, you can refer to the API documentation. The usage described here is already able to meet the needs of most file uploads, and, of course, if you have more complex requirements and the ability to use its flexible custom configuration, FileUpload will certainly be able to help you.

A simple example:

Import Java.io.File;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.util.Iterator;
Import java.util.List;

Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Import Org.apache.commons.fileupload.FileItem;
Import org.apache.commons.fileupload.FileUploadException;
Import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;
Import Org.apache.commons.fileupload.servlet.ServletFileUpload;

public class Fileuploadservlet extends HttpServlet {

Public Fileuploadservlet () {
Super ();
}

public void Destroy () {
Super.destroy (); Just puts "destroy" string in log
Put your code here
}

public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
DoPost (request, response);
}

public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
Final Long max_size = 3 * 1024 * 1024;//set upload file maximum of 3M
List of file formats that are allowed to be uploaded
Final string[] Allowedext = new string[] {"JPG", "JPEG", "gif", "TXT",
"Doc", "Docx", "MP3", "WMA", "M4A"};
Response.setcontenttype ("text/html");
Set character encoding to UTF-8, which supports Chinese character display
Response.setcharacterencoding ("UTF-8");

Instantiate a hard disk file factory to configure the upload component Servletfileupload
Diskfileitemfactory dfif = new Diskfileitemfactory ();
Dfif.setsizethreshold (4096)//Set the memory size for temporary storage of files when uploading files, here is 4K. More parts will be temporarily on the hard drive
Dfif.setrepository (New File (Request.getrealpath ("/")
+ "imagesuploadtemp")//Set the directory where temporary files are stored, the Imagesuploadtemp directory under the Web root directory

Use the above factory to instantiate the upload component
Servletfileupload SFU = new Servletfileupload (DFIF);
Set Maximum upload size
Sfu.setsizemax (max_size);

PrintWriter out = Response.getwriter ();
Get a list of all uploaded fields from request
List filelist = null;
try {
FileList = sfu.parserequest (request);
catch (Fileuploadexception e) {//processing file size is too large exception
if (e instanceof sizelimitexceededexception) {
OUT.PRINTLN ("File size exceeds the specified size:" + max_size + "byte <p/>");
Out.println ("<a href=/" upload.html/"target=/" _top/"> Return </a>");
Return
}
E.printstacktrace ();
}
No file Upload
if (filelist = null | | filelist.size () = 0) {
OUT.PRINTLN ("Please select upload file <p/>");
Out.println ("<a href=/" upload.html/"target=/" _top/"> Return </a>");
Return
}
Get all the uploaded files
Iterator Fileitr = Filelist.iterator ();
Loop through all Files
while (Fileitr.hasnext ()) {
Fileitem fileitem = null;
String path = null;
Long size = 0;
Get current file
Fileitem = (Fileitem) fileitr.next ();
Ignore the simple form field instead of the file field of the upload domain (<input type= "text"/>)
if (Fileitem = null | | Fileitem.isformfield ()) {
Continue
}
Get the full path to the file
Path = Fileitem.getname ();
Get the size of the file
Size = Fileitem.getsize ();
if ("". Equals (path) | | Size = = 0) {
OUT.PRINTLN ("Please select upload file <p/>");
Out.println ("<a href=/" upload.html/"target=/" _top/"> Return </a>");
Return
}

Get the file name of the removal path
String t_name = path.substring (Path.lastindexof ("//") + 1);
Get file extension (full name if no extension)
String T_ext = t_name.substring (T_name.lastindexof (".") + 1);
Refuse to accept file types outside of the specified file format
int allowflag = 0;
int allowedextcount = Allowedext.length;
for (; Allowflag < allowedextcount; allowflag++) {
if (Allowedext[allowflag].equals (T_ext))
Break
}
if (Allowflag = = Allowedextcount) {
Out.println ("Please upload the following types of files <p/>");
for (Allowflag = 0; Allowflag < allowedextcount; allowflag++)
Out.println ("*." + Allowedext[allowflag]
+ "&nbsp;&nbsp;&nbsp;");
Out.println ("<p/><a href=/" upload.html/"target=/" _top/"> Return </a>");
Return
}

Long now = System.currenttimemillis ();
Build the file name saved after uploading based on system time
String prefix = string.valueof (now);
The complete path to the saved final file, saved in the imagesuploaded directory under the Web root directory
String u_name = Request.getrealpath ("/") + "imagesuploaded/"
+ prefix + "." + T_ext;
try {
Save File
Fileitem.write (New File (U_name));
Out.println ("File upload succeeded.") Saved as: "+ prefix +". "+ T_ext
+ "&nbsp;&nbsp; File Size:" + size + "byte <p/>");
Out.println ("<a href=/" upload.html/"target=/" _top/"> Continue to Upload </a>");
catch (Exception e) {
E.printstacktrace ();
}

}

}

public void Init () throws Servletexception {
Put your code here
}

}

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.