Use Apache-fileupload to process files uploading and uploading multiple files two (59)

Source: Internet
Author: User

One use Apache-fileupload to process file uploads

Framework: Refers to a code encapsulation of a business that is often handled by a user. Make it easy for users to call.

Current file Upload (frame) components:

Apache----FileUpload-

orialiy–cos–2008 ()-

jsp-smart-upload–200m.

Uploading Files with FileUpload:

You need to import a third-party package:

apache-fileupload.jar– File Upload core package.

apache-commons-io.jar– This package is a fileupload dependency package. It's also a toolkit.

Core class:

diskfileitemfactory– Set disk space to save temporary files. Just a class.

Servletfileupload-The core class of file uploads, this class receives the request, and resolves the reqeust.

Servletfileupload.parserequest (requdest)-list<fileitem>

First Step: Import Packages

Step two: Write a servlet to complete the Dopost method

/** * diskfileitemfactory Construction two parameters * First parameter: sizethreadhold-set cache (memory) How many bytes of data to save, default is 10K * If a file is not greater than 10K, directly using memory directly saved into a file. * If a file is larger than 10K, you need to save the file to the Temp directory first. * The second parameter File refers to the temporary directory location **/ Public classUp2servlet extends HttpServlet { Public voidDoPost (httpservletrequest req, HttpServletResponse resp) throws Servletexception, IOException {req.s Etcharacterencoding ("UTf-8"); //get the path to the projectString Path= Getservletcontext (). Getrealpath ("/up"); //The first step declares the Diskfileitemfactory factory class, which is used to set up a temporary directory on the disk that refers todiskfileitemfactory Disk=NewDiskfileitemfactory (1024x768*Ten,NewFile ("d:/a")); //Step Two: Declare servletfileupoload, receive the temp directory aboveServletfileupload up=Newservletfileupload (disk); //Step three: Parse request       Try{List<FileItem> list =up.parserequest (req); //If you have a fileFileitem File= list.Get(0); //get file name, with pathString FileName=File.getname (); FileName= Filename.substring (Filename.lastindexof ("\\")+1); //get the type of fileString FileType=File.getcontenttype (); //get the byte code of the fileInputStreaminch=File.getinputstream (); //declaring the output byte streamOutputStream out=NewFileOutputStream (path+"/"+fileName); //file Copy           byte[] B =New byte[1024x768]; intLen =0;  while((len=inch. Read (b))!=-1){               out. Write (b,0, Len); }            out. Close (); LongSize =File.getinputstream (). available (); //Delete the uploaded temporary filesFile.delete (); //Show DataResp.setcontenttype ("Text/html;charset=utf-8"); PrintWriter op=Resp.getwriter (); Op.print ("File Upload success <br/> filename:"+fileName); Op.print ("<br/> file type: ""+FileType); Op.print ("<br/> File Size (bytes)"+size); } Catch(Exception e) {e.printstacktrace (); }    }}

Two upload multiple files

First step: Modify the page's form to multiple input type= "file"

<form action="<c:url value= '/up3servlet '/>"Method="Post"Enctype="Multipart/form-data">File1:<input type="file"Name="txt"><br/>File2:<input type="file"Name="txt"><br/> <input type="Submit"/> </form>

Step Two: Traverse list<fileitem>

 Public classUp3servlet extends HttpServlet { Public voidDoPost (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException { Request.setcharacterencoding ("UTF-8"); String Path= Getservletcontext (). Getrealpath ("/up"); //declaring diskDiskfileitemfactory disk =Newdiskfileitemfactory (); Disk.setsizethreshold (1024x768*1024x768); Disk.setrepository (NewFile ("d:/a")); //declaring a servlet that resolves requstServletfileupload up =Newservletfileupload (disk); Try{            //parsing Requstlist<fileitem> list =up.parserequest (Request); //declaring data for a file uploaded by a list<map> packagelist<map<string,string>> ups =NewArraylist<map<string,string>>();  for(Fileitem file:list) {Map<String,String> mm =NewHashmap<string, string>(); //Get file nameString FileName =File.getname (); FileName= Filename.substring (Filename.lastindexof ("\\")+1); String FileType=File.getcontenttype (); InputStreaminch=File.getinputstream (); intSize =inch. Available (); //using the tool classFileutils.copyinputstreamtofile (inch,NewFile (path+"/"+fileName)); Mm.put ("FileName", FileName); Mm.put ("FileType", FileType); Mm.put ("size",""+size);                Ups.add (mm);             File.delete (); } request.setattribute ("ups", UPS); //forwardingRequest.getrequestdispatcher ("/jsps/show.jsp"). Forward (request, response); }Catch(Exception e) {e.printstacktrace (); }    }}

Use Apache-fileupload to process files uploading and uploading multiple files two (59)

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.