Commons-fileupload-1.2.1.jar plugin upload and download

Source: Internet
Author: User

1: First write a text field on the page:

Import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >        File:<input type= "file" name= "file"/>         Description:<input type= "text" name= "desc"/>        <input type= "Submit" value= "Submit"/>    </form>  </body>

<form action= "Uploadservlet" method= "post" enctype= "Multipart/form-data" >
File:<input type= "File" name= "file"/>
Description: <input type= "text" name= "desc"/>
<input type= "Submit" value= "Submit"/>
</form>

1). Request mode is post: <form action= "Uploadservlet" method= "POST" ... >
2). form fields using file: <input type= "file" name= "file"/>
3). Request encoding using Multipart/form-data: <form action= "Uploadservlet" method= "post" enctype= "Multipart/form-data" >

2: Get the information on the page using the FileUpload plugin

 PackageFileUpload;ImportJava.io.File;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;Importjava.util.List;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.apache.commons.fileupload.FileItem;Importorg.apache.commons.fileupload.FileUploadException;Importorg.apache.commons.fileupload.disk.DiskFileItemFactory;ImportOrg.apache.commons.fileupload.servlet.ServletFileUpload; Public classUploadservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; protected voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {//1. Get Fileitem's collection items//Create a factory for disk-based file itemsDiskfileitemfactory factory =Newdiskfileitemfactory (); //Set factory constraints setting factory information
Writes to a temporary file in excess of 500K
Factory.setsizethreshold (1024 * 500); File tempdirectory=NewFile ("E:\\beforeproject"); Factory.setrepository (tempdirectory); //Create A new file upload handlerServletfileupload upload =Newservletfileupload (Factory); //Set overall request size constraint setting the total sizeUpload.setsizemax (1024 * 1024 * 5); //Parse the request Try{List<FileItem>/*Fileitem*/Items =upload.parserequest (Request); //2. Traverse Items: for(Fileitem item:items) {//If you have a general form field, print the information if(Item.isformfield ()) {String name=Item.getfieldname (); String value=item.getstring (); SYSTEM.OUT.PRINTLN (Name+ ": " +value); } //If the file domain, save the file to the D:\\files directory. Else{String FieldName=Item.getfieldname (); String FileName=Item.getname (); String ContentType=Item.getcontenttype (); LongsizeInBytes =item.getsize (); System.out.println (FieldName); System.out.println (FileName); System.out.println (ContentType); System.out.println (sizeInBytes); InputStream in=Item.getinputstream (); byte[] buffer =New byte[1024]; intLen = 0; FileName= "E:\\files\\" +FileName; System.out.println (FileName); OutputStream out=NewFileOutputStream (fileName); while(len = in.read (buffer))! =-1) {out.write (buffer,0, Len); } out.close (); In.close (); } } } Catch(fileuploadexception e) {e.printstacktrace (); } }}

Ii. Basic Ideas:

> Commons-fileupload can parse the request and get a List of Fileitem objects
> commons-fileupload resolves all request information to a Fileitem object, whether it is a generic text field or a file field.
> can call Fileitem's Isformfield () method to determine whether it is a form field or not a table fields (then a file field)
> to get further information

if (Item.isformfield ()) {
String name = Item.getfieldname ();
String value = item.getstring ();
...
}

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

InputStream Uploadedstream = Item.getinputstream ();
...
Uploadedstream.close ();
}

Iii. how to get the List<fileitem> object.

> A simple way

Create a factory for disk-based file items
Fileitemfactory factory = new Diskfileitemfactory ();

Create a new file upload handler
Servletfileupload upload = new Servletfileupload (factory);

Parse the request
List/* Fileitem */items = upload.parserequest (request);

> Complex way: You can add some restrictions and other attributes to file uploads

Create a factory for disk-based file items
Diskfileitemfactory factory = new Diskfileitemfactory ();

Set the maximum size of the uploaded file in memory and write the file to a temporary folder if it is exceeded. In units of byte
Factory.setsizethreshold (yourmaxmemorysize);
Set the Temp folder
Factory.setrepository (yourtempdirectory);

Create a new file upload handler
Servletfileupload upload = new Servletfileupload (factory);

Sets the total size of the uploaded file. You can also set the size of a single file.
Upload.setsizemax (yourmaxrequestsize);

Parse the request
List/* Fileitem */items = upload.parserequest (request);

Commons-fileupload-1.2.1.jar plugin upload and download

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.