servlet implementation file Upload, multiple file Upload example _javascript tips

Source: Internet
Author: User
Tags temporary file storage

One, the servlet implementation file upload, need to add a third party provided jar package

Download Address:

1) Commons-fileupload-1.2.2-bin.zip: Click to open the link

2) Commons-io-2.3-bin.zip: Click to open the link

Then put the two jar packages under the Lib folder:

Second: File Upload form submission method must be post way,

Encoding type: enctype= "Multipart/form-data", default is application/x-www-form-urlencoded

Like what:

<form action= "FileUpload" enctype= "Multipart/form-data" method= "POST" >

Third, for example:

1.fileupload.jsp

<%@ page language= "java" import= "javautil*" pageencoding= "UTF-8"%> <% String Path = Requestgetcontextpath (); 
String basepath = requestgetscheme () + "://" +requestgetservername () + ":" +requestgetserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML transitional//en" >  

2. Actual processing of file upload Fileupload.java

Package comservletfileupload; 
Import Javaiofile; 
Import javaio*; 
Import javaioioexception; 
Import Javaioprintwriter;  
Import javautillist; 
Import javaxservletservletexception; 
Import Javaxservlethttphttpservlet; 
Import Javaxservlethttphttpservletrequest; 
Import Javaxservlethttphttpservletresponse; 
Import Orgapachecommonsfileuploadfileitem; 
Import orgapachecommonsfileuploadfileuploadexception; 
Import Orgapachecommonsfileuploaddiskdiskfileitemfactory; 
 
Import Orgapachecommonsfileuploadservletservletfileupload; /** * * @author Administrator * File Upload * Specific steps: * 1 obtain Disk File entry Factory Diskfileitemfactory to guide package * 2) Use request to obtain the true path for Temporary file storage, and final file storage, these two storage locations can be different, or the same * 3 set some properties on the Diskfileitemfactory object * 4) High level API file upload processing servletfileupload upload = new 
 Servletfileupload (Factory); 
 * The purpose is to invoke the Parserequest (request) method to obtain the Fileitem collection list, * * 5) to obtain the information in the Fileitem object, to traverse, to determine whether the information submitted by the form is ordinary text information and to handle it. * 6) * The first itemwrite (new File (Path,filename) provided by a third party);  Write directly to disk *The second manual processing * */public class FileUpload extends HttpServlet {public void DoPost (HttpServletRequest request, Http Servletresponse response) throws Servletexception, IOException {requestsetcharacterencoding ("utf-8"); 
    /Set code//Get Disk File entry Factory Diskfileitemfactory factory = new Diskfileitemfactory (); 
     
    Gets the path to which the file needs to be uploaded String Path = Requestgetrealpath ("/upload"); If you do not have the following two lines, upload large files will occupy a lot of memory,//set up storage room temporarily, this storage room, can and final storage file directory different/** * Principle it is to save to the temporary storage room, and then in the real write to the corresponding directory of hard On the disk, * in fact, when uploading a file, is actually uploaded two copies, the first is in the TEM format * and then it is actually written to the corresponding directory of the hard disk/factorysetrepository (new file (PA 
    th)); 
     
    Set the size of the cache, when the upload file capacity exceeds the cache, directly to the temporary storage Room factorysetsizethreshold (1024*1024); 
     
     
    High-level API file upload processing servletfileupload upload = new Servletfileupload (factory); 
       
      try {//can upload multiple files list<fileitem> List = (list<fileitem>) uploadparserequest (request); For (Fileitem iteM:list) {//Get the form's property name String name = Itemgetfieldname (); If the obtained form information is a plain text message if (Itemisformfield ()) {//Gets the user-specific input string, the name is very good because the form submits a character 
           
          String value = Itemgetstring () of serial type; 
        Requestsetattribute (name, value); 
           ///To process incoming, not simple strings, such as binary pictures, movies these else {/** * below three steps, mainly get the name of the uploaded file 
          *//Get path name String value = Itemgetname (); 
          Index to the last backslash int start = Valuelastindexof ("\"); 
           
          Intercept the string name of the uploaded file, plus 1 to remove the backslash, string filename = valuesubstring (start+1); 
           
          Requestsetattribute (name, filename); 
           
          The exception that is actually written to disk//It throws is caught with exception//itemwrite (new File (Path,filename)); Manual Write OutputStream out = new FileOutputStream (new File (Path,filename)); 
           
          InputStream in = Itemgetinputstream (); 
          int length = 0; 
           
          byte [] buf = new byte[1024]; 
 
          Systemoutprintln ("Get the total volume of uploaded files:" +itemgetsize ());  Inread (BUF) each read data is stored in the BUF array while ((length = Inread (BUF))!=-1) {//in BUF array 
             
          Remove data to write to (output stream) on disk Outwrite (buf, 0, length); 
          } inclose (); 
        Outclose (); 
      catch (Fileuploadexception e) {//TODO auto-generated catch block 
    Eprintstacktrace (); 
    catch (Exception e) {//TODO auto-generated catch block//eprintstacktrace (); 
     
 
  } requestgetrequestdispatcher ("filedemojsp") forward (request, response); 
 } System.out.println ("Gets the total volume of uploaded files:" +item.getsize ());

3.filedemo.jsp

<%@ page language= "java" import= "javautil*" pageencoding= "UTF-8"%> <% String Path = Requestgetcontextpath (); 
String basepath = requestgetscheme () + "://" +requestgetservername () + ":" +requestgetserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML transitional//en" >  

4 results page:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.