Apache commons fileupload implements File Upload

Source: Internet
Author: User

This article is from
Blog, please be sure to keep this source http://zhangjunhd.blog.51cto.com/113473/18331


Place the Apache commons-fileupload.jar under the WEB-INF \ Lib of the application. The following is an example of how to use its file upload function.
The used fileupload version is 1.2, and the Environment is eclipse3.3 + myeclipse6.0. Fileupload is based on commons Io, so before entering the project determine the commons Io jar package (This article uses the commons-io-1.3.2.jar) under the WEB-INF \ Lib.
This example project can be downloaded from the attachment at the end of the article.

Example 1
The simplest example is to use the servletfileupload static class to parse the request. The factory class fileitemfactory will process all the fields in the mulipart form, not just the file field. Getname () gets the file name, getstring () gets the form data content, and isformfield () can judge whether it is a normal form item.

Demo1.html

<HTML> 

Demo1.jsp

<% @ Page Language = "Java" contenttype = "text/html; charset = gb18030" pageencoding = "gb18030" %> <% @ page import = "org. apache. commons. fileupload. * "%> <% @ page import =" org. apache. commons. fileupload. servlet. * "%> <% @ page import =" org. apache. commons. fileupload. disk. * "%> <% @ page import =" Java. util. * "%> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"> <% Boolean ismultipart = servletfileupload. ismultipartcontent (request); // check whether the input request is multipart form data. If (ismultipart = true) {fileitemfactory factory = new diskfileitemfactory (); // create a diskfileitemfactory object for the request and use it to parse the request. After parsing, all form items are saved in a list. Servletfileupload upload = new servletfileupload (factory); List <fileitem> items = upload. parserequest (request); iterator <fileitem> itr = items. iterator (); While (itr. hasnext () {fileitem item = (fileitem) itr. next (); // check whether the current project is a normal form project or an uploaded file. If (item. isformfield () {// if it is a normal form project, the form content is displayed. String fieldname = item. getfieldname (); If (fieldname. equals ("name") // corresponds to type = "text" name = "name" out. print ("the field name is" + item. getstring (); // display the form content. Out. Print ("<br>");} else {// if the file is uploaded, the file name is displayed. Out. print ("the Upload File name is" + item. getname (); out. print ("<br>") ;}} else {out. print ("The enctype must be multipart/form-Data ");} %> <HTML> 

Result:
The field name isjeff
The Upload File Name ISD: \ C language test sample question \ homework question .rar

Example 2
Upload two files to the specified directory.
Demo2.html

<HTML> 

Demo2.jsp

<% @ Page Language = "Java" contenttype = "text/html; charset = gb18030" pageencoding = "gb18030" %> <% @ page import = "org. apache. commons. fileupload. * "%> <% @ page import =" org. apache. commons. fileupload. servlet. * "%> <% @ page import =" org. apache. commons. fileupload. disk. * "%> <% @ page import =" Java. util. * "%> <% @ page import =" Java. io. * "%> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"> <% string uploadpath = "d :\\ Temp"; Boolean ismultipart = servletfileupload. ismultipartcontent (request); If (ismultipart = true) {try {fileitemfactory factory = new diskfileitemfactory (); servletfileupload upload = new servletfileupload (factory); List <fileitem> items = upload. parserequest (request); // obtain all the files iterator <fileitem> itr = items. iterat Or (); While (itr. hasnext () {// process each file in sequence fileitem item = (fileitem) itr. next (); string filename = item. getname (); // get the file name, including the path if (filename! = NULL) {file fullfile = new file (item. getname (); file savedfile = new file (uploadpath, fullfile. getname (); item. write (savedfile) ;}} out. print ("Upload succeed");} catch (exception e) {e. printstacktrace () ;}} else {out. println ("The enctype must be multipart/form-Data ");} %> <HTML> 

Result:
Upload succeed
Now, you can see the two files you uploaded under "D: \ Temp.

Example 3
Upload a file to the specified directory and specify the file size.
Demo3.html

<HTML> 

Demo3.jsp

<% @ Page Language = "Java" contenttype = "text/html; charset = gb18030" pageencoding = "gb18030" %> <% @ page import = "org. apache. commons. fileupload. * "%> <% @ page import =" org. apache. commons. fileupload. servlet. * "%> <% @ page import =" org. apache. commons. fileupload. disk. * "%> <% @ page import =" Java. util. * "%> <% @ page import =" Java. io. * "%> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"> <% file uploadpath = new file ("D: \ Temp "); // upload the file directory if (! Uploadpath. exists () {uploadpath. mkdirs ();} // temporary file directory file temppathfile = new file ("D: \ temp \ buffer \"); If (! Temppathfile. exists () {temppathfile. mkdirs ();} Try {// create a factory for disk-based file items diskfileitemfactory factory = new diskfileitemfactory (); // set factory constraints factory. setsizethreshold (4096); // set the buffer size, which is 4 kb factory. setrepository (temppathfile); // set the buffer directory // create a new file upload handler servletfileupload upload = new servletfileupload (factory); // set overall Request S Ize constraint upload. setsizemax (4194304); // set the maximum file size. Here is the 4 MB list <fileitem> items = upload. parserequest (request); // obtain all the files iterator <fileitem> I = items. iterator (); While (I. hasnext () {fileitem Fi = (fileitem) I. next (); string filename = Fi. getname (); If (filename! = NULL) {file fullfile = new file (Fi. getname (); file savedfile = new file (uploadpath, fullfile. getname (); FI. write (savedfile) ;}} out. print ("Upload succeed");} catch (exception e) {e. printstacktrace () ;}%> <HTML> 

Example 4
Use servlet to upload files.
Upload. Java

Package COM. ZJ. sample; import Java. io. file; import Java. io. ioexception; 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. disk. diskfileitemfactory; import Org. apache. commons. fileupload. servlet. servletfileupload; @ suppresswarnings ("serial") public class upload extends httpservlet {private string uploadpath = "D: \ Temp"; // Private string temppath = "D: \ temp \ buffer \ "; // temporary file directory file temppathfile; @ suppresswarnings (" unchecked ") Public void dopost (httpservletrequest request, httpservletresponse response) throws ioexception, servletexception {Try {// create a factory for disk-based file items diskfileitemfactory factory = new diskfileitemfactory (); // set factory constraints factory. setsizethreshold (4096); // set the buffer size, which is 4 kb factory. setrepository (temppathfile); // set the buffer directory // create a new file upload handler servletfileupload upload = new servletfileupload (factory); // set overall request size constraint upload. setsizemax (4194304 );// Set the maximum file size. Here is the 4 MB list <fileitem> items = upload. parserequest (request); // obtain all the files iterator <fileitem> I = items. iterator (); While (I. hasnext () {fileitem Fi = (fileitem) I. next (); string filename = Fi. getname (); If (filename! = NULL) {file fullfile = new file (Fi. getname (); file savedfile = new file (uploadpath, fullfile. getname (); FI. write (savedfile) ;}} system. out. print ("Upload succeed");} catch (exception e) {// you can jump to the error page e. printstacktrace () ;}} public void Init () throws servletexception {file uploadfile = new file (uploadpath); If (! Uploadfile. exists () {uploadfile. mkdirs ();} file temppathfile = new file (temppath); If (! Temppathfile. exists () {temppathfile. mkdirs ();}}}

Demo4.html

<HTML> 

Web. xml

<servlet>    <servlet-name>Upload</servlet-name>    <servlet-class>com.zj.sample.Upload</servlet-class></servlet> <servlet-mapping>    <servlet-name>Upload</servlet-name>    <url-pattern>/fileupload</url-pattern></servlet-mapping>


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.