【JavaWeb】File upload

Table of contents

1. File upload

1. Overview of file upload

1.1 What is file upload

1.2 Why learn file upload

1.3 Technology of file upload

1.4 Elements of file upload

2. Analysis of the principle of file upload

2.1 Packet capture analysis

2.2 Analysis of the principle of file upload

3. Getting Started with File Upload

3.1 Code implementation

3.2 File Upload API

4. JS controls multiple file uploads

4.1 Description of Case Requirements

5. File upload compatible with browser problems and solutions

5.1 Problem description

5.2 Problem Solving

6. The problem and solution to the problem of the same name of the file uploaded in the same directory

6.1 Problem Description

6.2 Problem Solving

7. The problem of storing too many files in the same directory when uploading files and its solution

7.1 Problem Description

7.2 File resolution

7.3 Algorithm implementation


1. File upload

1. Overview of file upload

1.1 What is file upload

  • File upload: The process of writing a local file to the server through a stream.

1.2 Why learn file upload

There are many applications in actual development:

  • Qzone upload pictures
  • Recruitment website upload resume

1.3 Technology of file upload

  1. JSPSmartUpload: A component for uploading and downloading files on JSP.
  2. FileUpload                   : The function of uploading files in the Java environment.
  3. Servlet3.0: Provides the function of file upload
  4. Struts2: Provides the function of file upload

1.4 Elements of file upload

Three elements of file upload:

  1. The form submission method needs to be POST
  2. There needs to be an <input type="file"> element in the form, and there needs to be a name attribute and a value.
  3. Form enctype="multipart/form-data"

2. Analysis of the principle of file upload

2.1 Packet capture analysis

  • The enctype attribute is not set
POST /web06/jsp/upload.jsp HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
X-HttpWatch-RID: 22006-10011
Referer: http://localhost:8080/web06/jsp/upload.jsp
Accept-Language: zh-CN
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: localhost:8080
Content-Length: 53
DNT: 1
Connection: Keep-Alive
Cache-Control: no-cache
Cookie: JSESSIONID=D51DCB996556C94861B2C72C4D978010

info=info&upload=C%3A%5CUsers%5Cjt%5CDesktop%5Caa.txt

***** Note: There is no specific content of the file in the file upload.

  • Set the enctype attribute
POST /web06/jsp/upload.jsp HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
X-HttpWatch-RID: 22006-10026
Referer: http://localhost:8080/web06/jsp/upload.jsp
Accept-Language: zh-CN
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko
Content-Type: multipart/form-data; boundary=---------------------------7e139d10110a64
Accept-Encoding: gzip, deflate
Host: localhost:8080
Content-Length: 322
DNT: 1
Connection: Keep-Alive
Cache-Control: no-cache
Cookie: JSESSIONID=D51DCB996556C94861B2C72C4D978010

-----------------------------7e139d10110a64
Content-Disposition: form-data; name="info"

aaa
-----------------------------7e139d10110a64
Content-Disposition: form-data; name="upload"; filename="C:\Users\jt\Desktop\aa.txt"
Content-Type: text/plain

hello world!!!
-----------------------------7e139d10110a64--

2.2 Analysis of the principle of file upload

3. Getting Started with File Upload

3.1 Code implementation

  • Step 1: Introduce related jar packages for file uploads

  • Step 2: Write the page for file upload

  •  Write a Servlet for file upload

3.2 File Upload API

3.2.1 DiskFileItemFactory: disk file item factory

  • Construction method:

①DiskFileItemFactory()

②DiskFileItemFactory(int sizeThreshold,File repostory):

sizeThreshold : Set the size of the file upload buffer, the default value is 10kb.

repository : Set the path for storing temporary files generated during file upload. 

  • method:

setSizeThreshold() : Set the size of the buffer

setRepository() : Set the path where temporary files are stored 

3.2.2 Code used by API

3.3.3 ServletFileUpload: core parsing class

  • Construction method:

 ServeltFileUpload(FileItemFactory fileItemFactory);

  • method:

■It is used to judge whether the enctype attribute of the form is correct.

 ■ Parse the Request object and return a List collection (object FileItem for each part)

■Set the size of the current file

■Set the total size of uploaded files

■Fixed the problem of garbled characters when uploading Chinese file names.

■ Set the progress of monitoring file upload

3.3.4 Common methods of the FileItem class

        1. boolean isFormField(). The isFormField method is used to determine whether the data encapsulated in the FileItem object is a normal text form field or a file form field. If it is a normal text form field, returns a true otherwise returns a false. Therefore, this method can be used to determine whether it is a normal form field or a file upload form field.

      2. String getName(). The getName method is used to obtain the file name in the file upload field.

      3. String getFieldName(). The getFieldName method is used to return the value of the name attribute of the form tag.

      4. void write(File file). The write method saves the contents of the FileItem object to a specified file. If the content of the FileItem object is saved in a temporary file, the temporary file may be deleted after this method is completed. This method can also save common form fields in a file, but the main purpose is to save the uploaded file content in the local file system.

      5. String getString(). The getString() method returns the content of the data stream saved in the FileItem object as a string. It has two overloaded forms. public  java.lang.String getString() and public java.lang.String getString(java.lang.String encoding) throws java.io.UnsupportedEncodingException. The former uses the default character set encoding to convert the main content into a string, and the latter uses the character set encoding specified by the parameter. If there are garbled characters when reading the content of ordinary form field elements, you can call the second method and pass in the correct character set encoding name.

      6. String getContentType(). This method is used to obtain the type of the uploaded file, that is, the value of the "content-type" attribute of the tag field element description header, such as image/jpeg. If the FileItem object corresponds to a normal form field, null will be returned.

      7. boolean isInMemory(). Determine whether the data encapsulated by the FileItem object is stored in the memory or on the hard disk.

      8. void delete(). This method is used to clear the main content encapsulated in the FileItem object. If the content is saved in a temporary file, this method will delete the temporary file.

      9. InputStream getInputStream(). Returns the body content of the uploaded file as a stream.

      10. long getSize(). Returns the size of the uploaded file.

4. JS controls multiple file uploads

4.1 Description of Case Requirements

4.2 Case code implementation

5. File upload compatible with browser problems and solutions

5.1 Problem description

If you use an old version of IE browser, there will be a file name acquisition error problem. When the old version of IE gets the file name, it will include the path.

5.2 Problem Solving

6. The problem and solution to the problem of the same name of the file uploaded in the same directory

6.1 Problem Description

Zhang San uploaded a file aa.txt to the server and the content is hello world. Li Si uploaded a file aa.txt content hello Java to the server. Files uploaded later overwrite files uploaded earlier.

6.2 Problem Solving

Use unique filenames for resolution.

7. The problem of storing too many files in the same directory when uploading files and its solution

7.1 Problem Description

Now all users upload files. If the website has a large number of visits, if they are all uploaded to the same directory, there are too many files stored in the same directory, which will also affect the program (in fact, when the directory is opened, It will be very stuck, let alone read and write operations).

7.2 File resolution

  • Directory separation:

Separation by time: by month, week, day, hour.

Separation by user: according to Zhang San and Li Si.

Separation by number: store 3000 files in one directory.

Separation algorithm by directory        : Separation according to a specific algorithm:

①Upload a file and get a unique file name.

②The unique file name gets its hashCode value. ----- value of type int ( 32 bits)

③Let the value of hashCode & 0xf;----- this value is used as the first-level directory.

④ Shift the hashCode to the right by 4 bits   & 0xf;---- The obtained value is used as the secondary directory.

⑤ and so on.

  • Analysis algorithm:

7.3 Algorithm implementation

Guess you like

Origin blog.csdn.net/wang_qiu_hao/article/details/127177250