Commons-fileupload file upload and download

Source: Internet
Author: User

Today I reviewed the commons-fileupload file upload and wrote a demo. The required jar packages are: commons-fileupload-1.2.1.jar, commons-io-1.4.jar. Can be downloaded under commons under Apache.

 

I. Upload

 

1. index. jsp

<% @ Page Language = "Java" Import = "Java. util. * "pageencoding =" UTF-8 "%> <br/> <% <br/> string Path = request. getcontextpath (); <br/> string basepath = request. getscheme () + ": //" + request. getservername () + ":" + request. getserverport () + path + "/"; <br/>%> </P> <p> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"> <br/> <HTML> <br/> <pead> <br/> <base href = "<% = basepath %>"> </P> <p> <title> my JSP 'index. JSP 'starting page </title> <br/> <meta http-equiv = "Pragma" content = "no-Cache"> <br/> <meta http-equiv =" cache-control "content =" no-Cache "> <br/> <meta http-equiv =" expires "content =" 0 "> <br/> <meta http-equiv = "keywords" content = "keyword1, keyword2, keyword3 "> <br/> <meta http-equiv =" Description "content =" this is my page "> <br/> </pead> </P> <p> <body> <br/> <form action = "/commons-fileupload/uploadservlet" method = "Post" enctype = "multipart/form-Data"> <br/> Username: <br/> <input type = "text" name = "username"> <br/> password: <br/> <input type = "password" name = "password"> <br/> file1: <br/> <input type = "file" name = "file1"> <br/> file2: <br/> <input type = "file" name = "file2"> <br/> <input type = "Submit" value = "Submit"> <br/> </form> <br/> </body> <br/> </ptml> <br/>

2. uploadservlet. Java

Package COM. fileupload. servlet; </P> <p> Import Java. io. file; <br/> Import Java. io. fileoutputstream; <br/> Import Java. io. ioexception; <br/> Import Java. io. inputstream; <br/> Import Java. io. outputstream; <br/> Import Java. util. list; </P> <p> Import javax. servlet. servletexception; <br/> Import javax. servlet. HTTP. httpservlet; <br/> Import javax. servlet. HTTP. httpservletrequest; <br/> Import javax. servlet. HTTP. HTTPS Ervletresponse; </P> <p> Import Org. apache. commons. fileupload. fileitem; <br/> Import Org. apache. commons. fileupload. disk. diskfileitemfactory; <br/> Import Org. apache. commons. fileupload. servlet. servletfileupload; </P> <p> @ suppresswarnings ("serial ") <br/> public class uploadservlet extends httpservlet {</P> <p> @ suppresswarnings ({"unchecked", "deprecation"}) <br/> Public void dopost (httpservletrequest request, Httpservletresponse response) throws servletexception, ioexception {<br/> request. setcharacterencoding ("UTF-8"); <br/> // set the file storage path <br/> string Path = request. getrealpath ("/upload"); <br/> // instantiate the factory <br/> diskfileitemfactory factory = new diskfileitemfactory (); <br/> // set the size of the files stored in the memory to 1 MB. If the size exceeds 1 MB, the files are written to the disk. <br/> factory. setsizethreshold (1024*1024); <br/> // if the file exceeds 1 MB, It will be written to the disk <br/> factory. setrepository (new file (Path ); </P> <p> servletfileupload = new servletfileupload (factory); <br/> try {<br/> // parse the request to fileitem, each fileitem corresponds to an input object on the page. <Br/> List <fileitem> List = servletfileupload. parserequest (request); <br/> for (fileitem item: List) {<br/> If (item. isformfield () {// If the input field is of the normal type = text (non-file type) <br/> string name = item. getfieldname (); <br/> string value = item. getstring ("UTF-8"); <br/> request. setattribute (name, value); </P> <p >}else {// If the input field is type = file type </P> <p> string name = item. getfieldname (); <br/> string value = item. getname (); // The following content will be obtained: eg: C:/Documents and Settings/Liu/desktop/test.doc <br/> int start = value. lastindexof ("//"); <br/> string filename = value. substring (start + 1); // convert to test.doc <br/> request. setattribute (name, filename ); </P> <p> /// write a file using a normal stream <br/> // outputstream out = new fileoutputstream (new file (path + "/" + filename )); <br/> // inputstream in = item. getinputstream (); <br/> // byte buffer [] = new byte [1024]; <br/> // int length = 0; <br/> // while (length = in. read (buffer)> 0) {<br/> // out. write (buffer, 0, length); <br/> //} <br/> // out. flush (); <br/> // out. close (); <br/> // In. close (); </P> <p> // use the method provided by fileitem to conveniently output <br/> item. write (new file (path + "/" + filename); </P> <p >}< br/>} catch (exception E) {<br/> E. printstacktrace (); <br/>}< br/> request. getrequestdispatcher ("success. JSP "). forward (request, response); <br/>}</P> <p >}< br/>

3. Success. jsp

<% @ Page Language = "Java" Import = "Java. util. * "pageencoding =" UTF-8 "%> <br/> <% <br/> string Path = request. getcontextpath (); <br/> string basepath = request. getscheme () + ": //" + request. getservername () + ":" + request. getserverport () + path + "/"; <br/>%> </P> <p> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"> <br/> <HTML> <br/> <pead> <br/> <base href = "<% = basepath %>"> </P> <p> <title> my JSP 'success. JSP 'starting page </title> </P> <p> <meta http-equiv = "Pragma" content = "no-Cache"> <br/> <meta http- equiv = "cache-control" content = "no-Cache"> <br/> <meta http-equiv = "expires" content = "0"> <br/> <Meta HTTP-equiv = "keywords" content = "keyword1, keyword2, keyword3 "> <Br/> <meta http-equiv =" Description "content =" this is my page "> <br/> <! -- <Br/> <LINK rel = "stylesheet" type = "text/CSS" href = "styles.css" mce_href = "styles.css"> <br/> --> </P> <p> </pead> </P> <p> <body> <br/> Username: $ {username} <br> <br/> password :$ {password} <br> <br/> file1 :1 {file1} <br> <br/> file2: $ {file2} <br> </P> <p> </body> <br/> </ptml> <br/>

4. Web. xml

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <web-app version = "2.5" <br/> xmlns = "http://java.sun.com/xml/ns/javaee" <br/> xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" <br/> xsi: schemalocation = "http://java.sun.com/xml/ns/javaee <br/> http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <br/> <servlet-Name> uploadservlet </servlet-Name> <br/> <Servlet -Class> COM. fileupload. servlet. uploadservlet </servlet-class> <br/> </servlet> </P> <p> <servlet-mapping> <br/> <servlet-Name> uploadservlet </Servlet -Name> <br/> <URL-pattern>/uploadservlet </url-pattern> <br/> </servlet-mapping> <br/> <welcome-file-list> <br/> <welcome-File> index. JSP </welcome-File> <br/> </welcome-file-List> <br/> </Web-app> <br/>

Ii. Download:

Download the file with a servlet:

 

Response. setcontenttype ("text/html; charset = UTF-8"); </P> <p> request. setcharacterencoding ("UTF-8"); </P> <p> printwriter out = response. getwriter (); </P> <p> long id = long. valueof (request. getparameter ("ID"); </P> <p> fileinfo = filedao. find (ID); </P> <p> response. setcontenttype ("application/X-msdownload;"); </P> <p> // This line of code is the key to preventing Chinese garbled characters !! </P> <p> response. setheader ("content-disposition", "attachment; filename =" + new string (fileinfo. getname (). getbytes ("gb2312"), "iso8859-1"); </P> <p> bufferedinputstream Bis = new bufferedinputstream (New fileinputstream (fileinfo. getpath (); </P> <p> bufferedoutputstream Bos = new bufferedoutputstream (response. getoutputstream (); </P> <p> // create a 2048-byte buffer </P> <p> byte [] buff = new byte [2048]; </P> <p> int bytesread; </P> <p> while (bytesread = bis. Read (buff, 0, Buff. Length ))! =-1) </P> <p >{</P> <p> Bos. write (buff); </P> <p >}</P> <p> If (Bis! = NULL) </P> <p> bis. Close (); </P> <p> If (Bos! = NULL) </P> <p> Bos. Close (); </P> <p >}</P> <p>

 

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.