Java EE component commons-fileupload implementation file upload, download _java

Source: Internet
Author: User
Tags local time uuid

First, File upload overview

To implement the file upload function in Web development, two steps are required:

1, add the upload entry in the Web page

    <form action= "#" method= "POST" enctype= "Multipart/form-data" >
      <input type= "file" name= "filename1"/> <br>
      <input type= "file" Name= "filename2"/><br> <input type=
      "Submit" value= "Upload"/>
    <form>
    <!--1, form must be post
      2, Enctype property must be set to multipart/ Form-data. After setting this value, the browser will attach the file data to the HTTP request message body when uploading the file,
        and use the MIME protocol to describe the uploaded file so as to facilitate the recipient to parse and process the uploaded data.
      3, you must set the input Name property, otherwise the browser will not send data uploaded files.
    -->

2, in the servlet read file upload data, and save to the server hard disk

The Request object provides a getInputStream method that can be used to read data submitted by the client. However, since users may upload multiple files at the same time, it is a very troublesome task to directly read the uploaded data in the servlet side and parse out the corresponding file data separately.

For example, the following is part of the HTTP protocol that is sent when an intercepted browser uploads a file:

accept-language:zh-hans-cn,zh-hans;q=0.5 Content-type:multipart/form-data; boundary=---------------------------7dfa01d1908a4 ua-cpu:amd64 accept-encoding:gzip, deflate user-agent:mozilla/ 5.0 (Windows NT 6.2; Win64; x64; trident/7.0; rv:11.0) like Gecko content-length:653 host:localhost:8080 connection:keep-alive pragma:no-cache cookie:jsessionid=11 ceff8e271ab62ce676b5a87b746b5f-----------------------------7dfa01d1908a4 Content-disposition:form-data; Name= "username" Zhangsan-----------------------------7dfa01d1908a4 content-disposition:form-data; Name= "Userpass" 1234-----------------------------7dfa01d1908a4 Content-disposition:form-data; Name= "filename1";
Filename= "C:\Users\ASUS\Desktop\upload.txt" Content-type:text/plain This is a-a-content! -----------------------------7dfa01d1908a4 Content-disposition:form-data; Name= "filename1";
Filename= "C:\Users\ASUS\Desktop\upload2.txt" Content-type:text/plain this is Second file content! Hello-----------------------------7dfa01d1908a4-- 

As can be seen from the above data, it is difficult to write robust and stable programs if you are manually segmenting and reading data. Therefore, in order to facilitate the user processing upload data, the Apache Open source organization provides an open source component (Commons-fileupload) for processing the form file uploads, the component performance is excellent, and its API usage is extremely simple, can let the developer easily realize the Web file upload function, Therefore, the implementation of file uploading in web development is usually implemented using the Commons-fileupload component.

Need to import two jar packages: Commons-fileupload, Commons-io

Response.setcontenttype ("Text/html;charset=utf-8");/Set response encoding request.setcharacterencoding ("Utf-8"); PrintWriter writer = Response.getwriter ()//Get response output stream ServletInputStream InputStream = Request.getinputstream ();
     Fetch request INPUT Stream/* 1, create Diskfileitemfactory object, set buffer size and temp file directory * This class has two construction methods, one is a parameterless construction method, and the other is a construction method with two parameters * @param int Sizethreshold, which sets the size of the memory buffer, with a default value of 10K. When the upload file is larger than the buffer size, the FileUpload component uses the temporary file cache to upload the file * @param java.io.File repository, which specifies the temporary file directory, and the default value is System.getproperty ("
     Java.io.tmpdir "); 
     * If you use the parameterless construction method, use Setsizethreshold (int sizethreshold), setrepository (Java.io.File repository) * method to set manually
    
    * * Diskfileitemfactory factory = new Diskfileitemfactory ();
    int sizethreshold=1024*1024;
    
    Factory.setsizethreshold (Sizethreshold);
File repository = new file (Request.getsession (). Getservletcontext (). Getrealpath ("temp"));
System.out.println (Request.getsession (). Getservletcontext (). Getrealpath ("temp")); //System.out.println (Request.getrealpath ("temp"));
    
    Factory.setrepository (repository); * * 2, use the Diskfileitemfactory object to create the Servletfileupload object, and set the size of the upload file * * Servletfileupload object is responsible for processing uploaded file data, and the form of each       An input item is encapsulated into a fileitem * The common methods for this object are: * Boolean ismultipartcontent (request); Determine if the upload form is a multipart/form-data type * The list parserequest resolves the request object, wraps each entry in the form into a Fileitem object, and returns a list collection that holds all Fileitem * void Setfi Lesizemax (Long Filesizemax), set maximum value of single upload file * void Setsizemax (Long Sizemax), set maximum amount of upload Wenjiang * void SetHeader
    
    Encoding (), set the encoding format, to solve the upload file name garbled problem * * servletfileupload upload = new Servletfileupload (factory); Upload.setheaderencoding ("Utf-8")//Set encoding format, solve the upload file name garbled problem * * 3, call the Servletfileupload.parserequest method to resolve the request object, get a guarantee
    Save all uploaded content List Object * * list<fileitem> parserequest=null;
    try {parserequest = upload.parserequest (request); catch (Fileuploadexception e) {E.PRIntstacktrace (); * * * 4, iterate over the list, each iteration of a Fileitem object, call its Isformfield method to determine whether the file is uploaded * True is normal form field, then call GetFieldName, GetString method to get Word
     Segment Name and field value * False to upload file, call getInputStream method to get data input stream, read upload data * * Fileitem used to represent an uploaded file object or a normal form object in a File upload form * This object commonly used methods are: * Boolean Isformfield (), to determine whether Fileitem is a file upload object or Normal form object * True is a common form field, * then call GETF         Ieldname, GetString method to get Field name and field value * False to upload file, * call GetName () get file name of uploaded file, note: Some browsers will carry the client path, need to deduct * Call the getInputStream () method to get the data input stream to read the upload data * Delete ();
     Indicates that temporary files are deleted after the Fileitem input stream is closed. */for (Fileitem fileitem:parserequest) {if (Fileitem.isformfield ()) {//Represents the Normal field if ("username". eq
          Uals (Fileitem.getfieldname ())) {String username = fileitem.getstring ();
        Writer.write ("Your username:" +username+ "<br>");
          } if ("Userpass". Equals (Fileitem.getfieldname ())) {String Userpass = fileitem.getstring (); WRiter.write ("Your password:" +userpass+ "<br>");
        }else {///means the uploaded file///browser upload file may have a path name, you need to cut String ClientName = Fileitem.getname ();
        String filename = ""; if (Clientname.contains ("\")) {//if the containing "\" representation is a name with a path, the last filename is intercepted filename = clientname.substring (clientname.lastin
        Dexof ("\")). substring (1);
        }else {filename = clientname; The UUID Randomuuid = Uuid.randomuuid ()//generates a 128-bit long global unique identifier filename = randomuuid.tostring (
        
        ) +filename; * * Design a directory generation algorithm, if the user uploaded the total number of files are billion or more, placed in the same directory next to cause the file index is very slow, * So, design a directory structure to spread the file is very necessary, and reasonable * will u UID hash algorithm, hash to a smaller range, * Converts the hashcode of the UUID to a 8-bit 8-digit string, starting with the first digit of the string, each character represents a level of directory, thus building a level eight directory with a maximum of 16 children in each level of the directory
        Directory * This is a very efficient directory structure for both the server and the operating system */int hashuuid =randomuuid.hashcode ();
        String Hexuuid = integer.tohexstring (Hashuuid); System.out.println (HEXUUID);
        Gets the absolute path String filepath=request.getsession (). Getservletcontext (). Getrealpath ("Upload") where the uploaded file is stored under which folder.
        for (char C:hexuuid.tochararray ()) {filepath = filepath+ "/" +C;
        ///If directory does not exist generate level eight directory file Filepathfile = new file (filepath);
        if (!filepathfile.exists ()) {filepathfile.mkdirs ();
        //Read the file from the request input stream and write to the server InputStream inputStream2 = Fileitem.getinputstream ();
        Creates a file on the server side (filepath+) = new file (+filename);
        
        Bufferedoutputstream BOS = new Bufferedoutputstream (new FileOutputStream (file));
        byte[] buffer = new byte[10*1024];
        int len = 0;
        while ((len= inputstream2.read (buffer, 0, 10*1024))!=-1) {bos.write (buffer, 0, Len);
        } writer.write ("You upload file" +clientname+ "Success <br>");
        Close resource Bos.close ();
      Inputstream2.close (); }//Note that Eclipse's uploaded files are saved in the project's running directory, not the workspacePath directory. 

Second, the file upload needs special attention to the problem: (These questions provide a simple solution in the above code.)

1, the location of the file storage

To ensure server security, upload files should be stored in the application's Web-inf directory, or not by the Web server Management directory, if the user uploads a file with executable code, such as JSP files, according to the Mosaic access path to access, you can do anything on the server side.

2, in order to prevent multiple users upload files with file names, and resulting in document coverage of the situation, file upload program should ensure that the upload file has a unique filename .

Rename by using UUID + user upload file name

About UUID:
The UUID (universally unique Identifier) Globally unique identifier, which is the number generated on a single machine, guarantees that all machines in the same space-time are unique. According to the standard calculations developed by the Open Software Foundation (OSF), Ethernet card addresses, nanosecond time, chip ID codes, and many possible numbers are used. A combination of the following parts: The current date and time (the first part of the UUID is related to time, and if you generate a UUID after a few seconds after generating a UUID, the first part is different, the rest is the same), the clock sequence, and the globally unique IEEE Machine identification number (if there is a NIC, obtained from the NIC, No NIC is available in any other way, the only drawback of the UUID is that the resulting string will be relatively long.

is a 128-bit long number, usually expressed in 16. The core idea of the algorithm is to combine the machine's network card, local time, and a random number to generate the GUID. Theoretically, if a machine produces 10 million GUIDs per second, it can be guaranteed (in the sense of probability) not to repeat for 3,240 years.

Starting with JDK1.5, the generation of UUID becomes a simple matter, assuming that the JDK implements the UUID:

Java.util.UUID, direct call can be.
UUID uuid = Uuid.randomuuid ();
String s = Uuid.randomuuid (). toString ();//The primary key ID used to build the database is very good.

The UUID is made up of a 16-digit number, showing a form such as
550e8400-e29b-11d4-a716-446655440000

3, in order to prevent a single directory of too many files, affecting the speed of reading and writing, processing upload files should be based on the total amount of upload, select the appropriate directory structure generation algorithm, will upload files dispersed storage. Use the Hashcode method to build a multilevel directory.

4, if different users upload the same file, then the server side does not need to store a lot of copies of the same file, so wasteful resources, should design algorithms to solve this duplicate file problem.

5, the JSP technology principle realizes the multithreading automatically. So developers don't have to consider the multithreading of uploading files

Third, File download

<% arraylist<string> fileNames = new arraylist<string> ();
    Filenames.add ("File/aa.txt");
    Filenames.add ("file/bb.jpg"); for (String filename:filenames) {%> <form action= ' downloadservlet ' method= ' get ' > <input typ E= "hidden" name= "FileName" value= <%=filename%> "/> <input type=" submit "value=" Download: <%=filename%>
    
    "/> </form> <%}%> request.setcharacterencoding (" Utf-8 ");
    
    
    String filename = request.getparameter ("filename"); String urlname = Urlencoder.encode (FileName, "utf-8");//Prevent Chinese garbled response.setheader in file name ("Content-disposition", "
    
    Attachment;filename= "+urlname); FileInputStream fis = new FileInputStream (New File (Request.getsession (). Getservletcontext (). Getrealpath (filename))
    ;
    Bufferedinputstream bis = new Bufferedinputstream (FIS);
    
    Servletoutputstream SOS = Response.getoutputstream ();
    byte[] buffer = new byte[1024]; INT Len=0;
    while ((len=bis.read (buffer, 0, 1024))!=-1) {sos.write (buffer, 0, Len);
    } bis.close (); Fis.close ();

Iv. use smartupload components in SSH to simplify file upload and download

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.

Related Article

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.