Use DiskFileItemFactory Upload Files

<%@ page contentType="text/html;charset=UTF-8" %>
<HTML>
<HEAD>
    <title>上传文件</title>
</HEAD>
   <body>
     <div>
         <form action="upFile.do" method="post" enctype="multipart/form-data">
             <table>
                 <tr>
                     <td>姓名</td>
                     <td><input name="name" type="text"></td>
                     <td>年龄</td>
                     <td><input name="age" type="text"></td>
                     <td>上传文件</td>
                     <td><input name="file" type="file"></td>
                     <td><input type="submit" value="上传"></td>
                 </tr>
             </table>
         </form>
     </div>
   </body>
</HTML>

  

The core-DiskFileItemFactory the API
DiskFileItemFactory object is created FileItem factory, factory class common methods:
. 1, setSizeThreshold public void (int the sizeThreshold): set the size of the buffer memory, the default value is 10K. When uploading files larger than the buffer size, fileupload component will use a temporary file cache to upload files.
2, public void setRepository (Java.io.File repository ): Specifies the temporary file directory, the default value System.getProperty ( "java.io.tmpdir").
3, public DiskFileItemFactory (int sizeThreshold, java.io.File Repository) :Constructor

Core the API - ServletFileUpload
ServletFileUpload handles uploaded file data, and each entry is encapsulated into a form FileItem object. Common methods:
. 1, Boolean isMultipartContent (the HttpServletRequest Request): determines whether the upload form multipart / form-data type

2, List parseRequest (HttpServletRequest request): parsing the request object, and to form a package each of the entries into a fileItem object and returns a collection of all the saved list of FileItem.

3, setFileSizeMax (long fileSizeMax): Set the maximum value (single file) uploaded file is used to set the maximum size of a single file upload limit to prevent malicious clients to upload large files to the server storage space is wasted. Which is a parameter bytes long digital.

4, setSizeMax (long sizeMax): Set the maximum value (all files uploaded) the total amount of uploaded files, setup request message for content entity (i.e. all uploads data) is the maximum size limit to prevent malicious clients to upload large files to waste server storage space. Which is a parameter bytes long digital.

5, setHeaderEncoding (java.lang.String encoding): Set encoding format. File upload request in the message body, in addition to the ordinary form field value is other than text, file upload file path name text field is stored in memory array of bytes thereof is some character set encoding, Apache file upload component when reading the content, they must know the character set encoding used to convert them to the correct character text returned.

The core API-FileItem
common method FileItem class:
. 1, Boolean isFormField (): A method for determining FileItem isFormField class object encapsulates data field is a plain text form, or a form field file, returns true if the field is a common form, otherwise it returns false.

2, String getName ()
for the file name to obtain file upload field. Note that IE or FireFox get the file name is not the same, IE is the absolute path, FireFox in just the file name.

3, String getFieldName ()
Returns the value of the name attribute of the form tag.

4, void write (File file): used to save the saved FileItem main content object to a specified file. If the subject content FileItem object is stored in a temporary file, after the successful completion of the method, the temporary file is likely to be cleared. The method may also be written into an ordinary form field contents in a document, but the main purpose is to upload a content file stored in the local file system.

5, String getString (): for streaming content object stored FileItem to return a string, which is defined in the form of two overloaded:
public Java.lang.String to the getString ();
public java.lang.String getString (java.lang.String encoding) throws java.io.UnsupportedEncodingException
former uses the default character set encoding to convert the content into a string body, which uses character set encoding parameter specified by the contents of the body to convert into a string. If there is a Chinese garbled phenomenon at the time of reading the content elements common form fields, please call the second getString method, and passing it the correct character set encoding name.

6, void delete (): delete the main method used to empty the contents stored in FileItem class object, if the body content is stored in a temporary file, delete method deletes the temporary file. Although FileItem when the object is garbage collected automatically remove temporary files, but calls promptly delete the earlier method can clear temporary files to free up system memory resources.

Implementation steps:
1. Create DiskFileItemFactory objects, set the buffer size and the temporary file directory.
2, DiskFileItemFactory object creation ServletFileUpload object and set the size limit upload files.
3, call ServletFileUpload.parseRequest method resolution request object, get a hold of all the content uploaded the List object.
4, on the list iterates a FileItem each iteration of the object, call its isFormField method to determine whether a file is uploaded:
4.1, for the general form fields, the call getFieldName, getString method to obtain the field names and field values.
4.2, an uploaded file, getInputStream method is called to get the data input stream, thereby reading the data upload.
We need to introduce the jar package:

<dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>

  Code:

void the doPost public (the HttpServletRequest Request, the HttpServletResponse Response) throws ServletException, IOException { 

        the response.setContentType ( "text / HTML; charset = UTF-. 8"); 

        // create a parser facility 
        DiskFileItemFactory new new DiskFileItemFactory Factory = (); 
        // Set memory buffer size factory default is 10K 
       // factory.setSizeThreshold (1024 * 1024); 
        // set up factories temporary file directory: when the upload file size is larger than the buffer size, the use of temporary files directory cache file uploads 
        factory.setRepository (new new file ( "D: \\ \\ of YOHO")); 
       // file upload parser 
        ServletFileUpload = Upload new new ServletFileUpload (Factory); 
       // set all the data uploaded maximum value, in bytes 1M Long 
        Upload .setSizeMax (1024 * 1024); 
        // set the maximum for a single file upload 
        upload.setFileSizeMax (1024 * 1024);
        // set the encoding format 
        upload.setHeaderEncoding ( "UTF-. 8"); 

        the try { 
            // parse the request, the entry form for each object is encapsulated into a FileItem 
            List <FileItem> = upload.parseRequest the itemList (Request); 
            for ( item the FileItem: the itemList) { 
                // determine the type of input ordinary file entry or 
                IF (item.isFormField ()) { 
                    // Common entry, to give the name attribute value input 
                    String name = item.getFieldName (); 
                    // obtain the entry value 
                    String value = item.getString ( "UTF-. 8"); 
                    System.out.println ( "name =" + name + "value =" + value); 
                } the else { 
                    // uploading file, obtain the file name of the file upload field
                    // Note that the file name IE or FireFox acquired is not the same, IE is the absolute path, FireFox in just the file name. 
                    Item.getName fileName = String (); 
                    System.out.println (fileName); 
                    // return the form tag name attribute value 
                    String namede item.getFieldName = (); 
                    System.out.println (namede); 

                   // Method a: save upload files to the specified file path 
                    the InputStream item.getInputStream iS = (); 
                    a FileOutputStream fos = new new a FileOutputStream ( "D: \\ \\ WPS" + fileName); 
                    byte [] = BUFF new new byte [1024]; 
                    int len = 0; 
                    the while ((len = is.read (BUFF))> 0) { 
                        fos.write (BUFF); 
                    } 

                    // method two: save the path to the specified 
                    // save the stored contents FileItem object body to a specified file. 
                    // If the subject content FileItem object is stored in a temporary file, after the successful completion of the method, the temporary file is likely to be cleared 
                    item.write (new File ( "D: \\ sohucache \\" + fileName )); 
                    is.close (); 
                    fos.close (); 
                } 
            } 
        } the catch (Exception E) { 
            e.printStackTrace (); 
        } 

    } 
// results: 
// plain text 
name = name value = I waited 
name = value = 25 Age 
// filename: Firefox is the file name ,, IE browser is the absolute path 
asosResult.txt 
// JSP in the name attribute value 
file 

text: https: //blog.csdn.net/u014785687/article / details / 73863964

  

Guess you like

Origin www.cnblogs.com/xieguolin/p/10943000.html