Uploading files in JavaWeb

Uploading files in JavaWeb

1. Requirements for file uploading on the page

1, must use the form

2. The method of the form must be POST, not GET

3. The enctype of the form must be multipart/form-data;

4. Add the file form field to the form, ie <input type=”file”…/>

which is:

 HTML Code 
1
2
3
4
5
6
7
     <form action="${pageContext.request.contextPath }/FileUploadServlet"method="post"enctype="multipart/form-data">        用户名:<inputtype="text"name="username"/><br/>        文件1:<inputtype="file"name="file1"/><br/>        文件2:<inputtype="file"name="file2"/><br/><inputtype="submit"value=      
   
   
   
        
    "提交" /> </form>
    


2. Compare the difference between the file upload form and the normal text form

l enctype=”multipart/form-data” of the file upload form, which means multi-part form data;

l For ordinary text forms, the enctype attribute may not be set:

Ø When method=”post”, the default value of enctype is application/x-www-form-urlencoded, which means to use url to encode the body;

When method="get", the default value of enctype is null and there is no body, so enctype is not needed.

Third, the test of the file upload form

 HTML Code 
1
2
3
4
5
6
7
<form action="${pageContext.request.contextPath }/FileUploadServlet"method="post"enctype="multipart/form-data">        用户名:<inputtype="text"name="username"/><br/>        文件1:<inputtype="file"name="file1"/><br/>        文件2:<inputtype="file"name="file2"/><br/><inputtype="submit"value=      
   
   
   
        
    "提交" /> </form>
    


Through the test, check the body part of the form request data and find that the body part is composed of multiple parts, each part corresponds to a form field, and each part has its own header information. Below the header information is a blank line, and below the blank line is the body of the field. Parts are separated by randomly generated dividers.

The header information of the text field contains only one header information, namely Content-Disposition. The value of this header information has two parts, the first part is fixed, namely form-data, and the second part is the name of the field. After the blank line is the body part, and the body part is the content filled in the text box.

  The header information of the file field contains two header information, Content-Disposition and Content-Type. There is one more filename in Content-Disposition, which specifies the name of the uploaded file. The Content-Type specifies the type of uploaded file. The body part of the file field is the content of the file. 

Fourth, file upload requirements for Servlet

First of all, we must be sure that the data of the file upload form is also encapsulated into the request object.

The request.getParameter(String) method obtains the character content of the specified form field, but the file upload form is no longer character content, but byte content, so it is invalid.

At this time, you can use the getInputStream() method of the request to obtain the ServletInputStream object, which is a subclass of InputStream. This ServletInputStream object corresponds to the body part of the entire form (from the first separator to the end), which indicates the parsing stream we need. data in . Of course, parsing it is a very troublesome thing, and Apache has provided us with a tool for parsing it: commons-fileupload.

Five, commons-fileupload introduction

Why use fileupload:

There are many requirements for uploading files, you need to remember:

l Must be a POST form;

l The enctype of the form must be multipart/form-data;

l Add the file form field to the form, ie <input type=”file”…/>

Servlet requirements:

l Can no longer use request.getParameter() to get form data;

l You can use request.getInputStream() to get all the form data, not the data of a form item;

l This means that without using fileupload, we need to parse the content of request.getInputStream() by ourselves! ! !

1, fileupload overview

fileupload is an upload component provided by the commons component of apache. Its main job is to help us parse request.getInputStream().

The JAR packages required by the fileupload component are:

l commons-fileupload.jar, the core package;

l commons-io.jar, a dependency package.

2, fileupload simple application

The core classes of fileupload are: DiskFileItemFactory, ServletFileUpload, FileItem

The use steps are as follows:

1. Create a factory class DiskFileItemFactory object: DiskFileItemFactoryfactory = new DiskFileItemFactory()

2. Create a parser object using a factory: ServletFileUpload fileUpload = new ServletFileUpload(factory)

3. Use the parser to parse the request object: List<FileItem>list = fileUpload.parseRequest(request)

Introduce the FileItem class, which is the final result we want. A FileItem object corresponds to a form item (form field). There are file fields and common fields in a form. You can use the isFormField() method of the FileItem class to determine whether the form field is a common field. If it is not a common field, it is a file field.

l String getName(): Get the file name of the file field;

l String getString(): Get the content of the field. If it is a file field, then the content of the file is obtained. Of course, the uploaded file must be a text file;

l String getFieldName(): Get the field name, for example: <inputtype=”text” name=”username”/>, it returns username;

l String getContentType(): Get the type of the uploaded file, for example: text/plain.

l int getSize(): Get the size of the uploaded file;

l boolean isFormField(): Determine whether the current form field is a normal text field, if it returns false, it means it is a file field;

l InputStream getInputStream(): Get the input stream corresponding to the uploaded file;

l void write(File): Save the uploaded file to the specified file.

6. Simple upload example

first step:

Complete index.jsp, just need a form. Note that the form must be post, and the enctype must be mulitpart/form-data.

 HTML Code 
1
2
3
4
5
6
  <form action="${pageContext.request.contextPath }/FileUploadServlet"method="post"enctype="multipart/form-data">        用户名:<inputtype="text"name="username"/><br/>        文件1:<inputtype="file"name="file1"/><br/><inputtype="submit"value="提交"/></form>      
   
   
        
   
    


Step 2:

Complete FileUploadServlet

 HTML Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         //  Because you want to use response printing, set its encoding
        response.setContentType(
"text/html;charset=utf-8" );
        
        
//  Create factory
        DiskFileItemFactory dfif = new DiskFileItemFactory();
        
//  Use the factory to create the parser object
        ServletFileUpload fileUpload = new ServletFileUpload(dfif);
        try {
            
//  Use the parser object to parse the request and get the FileItem list
            List
< FileItem >  list = fileUpload.parseRequest(request);
            
//  loop through all form items
            for(FileItem fileItem : list) {
                
//  If the current form item is a normal form item
                if(fileItem.isFormField()) {
                    
//  Get the field name of the current form item
                    String fieldName = fileItem.getFieldName();
                    
//  If the current table The field name of a single item is username
                    if(fieldName.equals(
"username" )) {
                        
//  Print the content of the current form item, that is, the content entered by the user in the username form item
                        response.getWriter().print(
"Username:"  + fileItem.getString() +  "<br/>" );
                    }
                } else {
// If the current form item is not a normal form item, the description is the file field
                    String name = fileItem.getName();
// Get the name of the uploaded file
                    
//  如果上传的文件名称为空,即没有指定上传文件
                    if(name == null || name.isEmpty()) {
                        continue;
                    }
                    
//  获取真实路径,对应${项目目录} / uploads,当然,这个目录必须存在
                    String savepath = this.getServletContext().getRealPath(
"/uploads" );
                    
//  通过uploads目录和文件名称来创建File对象
                    File file = new File(savepath, name);
                    
//  把上传文件保存到指定位置
                    fileItem.write(file);
                    
//  打印上传文件的名称
                    response.getWriter().print(
"上传文件名:"  + name +  "<br/>" );
                    
//  打印上传文件的大小
                    response.getWriter().print(
"上传文件大小:"  + fileItem.getSize() +  "<br/>" );
                    
//  打印上传文件的类型
                    response.getWriter().print(
"上传文件类型:"  + fileItem.getContentType() +  "<br/>" );
                }
            }
        } catch (Exception e) {
            throw new ServletException(e);
        } 
    }

















Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324611200&siteId=291194637