How does Java file upload work?

In Web applications, since most file uploads are submitted to the server in the form of forms, if you want to implement the file upload function in the program, you must first create a form page for uploading files. It should be noted that in order for the Servlet program to obtain the data of the uploaded file, the method attribute of the form page needs to be set to the post mode, the enctype attribute is set to the "multipart/form-data" type, and the input tag type of the added file is set to file type. Examples are as follows:

<%--指定表单数据的 enctype 属性以及提交方式 --%>
<form enctype="multipart/form-data" method="post">
<%-- 指定标记的类型和普通表单的名称 --%>
用户名:<input type="text" name="name"/><br/>
<%--指定标记的类型和文件域的名称--%>
选择上传文件:<input type="file" name="myfile"/><br/>

When the browser submits the uploaded file through the form, the file data is attached to the HTTP request message body, and the MIME type (multipurpose Internet mail extension type) is used for description. Therefore, the HTTP message sent by the browser to the server is special. The specific examples are as follows:

multipart/form-data;boundary=----------------------------7dfa7a30650
----------------------------7dfa7a30650
Content-Disposition: form-data;name="name"

itcast
----------------------------7dfa7a30650
Content-Disposition: form-data;name="myfile";filename="uploadfile.txt"
Content-Type: text/plain
www.itcast.cn
----------------------------7dfa7a30650--

As can be seen from the above form request body, the request body is divided into multiple parts, and it is troublesome to parse the content of this part. To this end, the Apache organization provides an open source component Commons-FileUpload, which can easily parse out various form fields in the "multipart/form-data" type request, and realize the upload of one or more files. You can limit the size of the uploaded file and other content, and the performance is excellent, and the use is extremely simple. It should be noted that when using the FileUpload component, two jar packages, commons-fileupload and commons-io, need to be imported.

In order for everyone to better understand how the FileUpload component implements the file upload function, next, open the help file of the FileUpload component to view its implementation, as shown in Figure 6-1.
How does Java file upload work?
As can be seen from Figure 1, the FileUpload component also implements the file upload function through Servlet. Its workflow is shown in Figure 2.
How does Java file upload work?
As can be seen from Figure 2, there are several unfamiliar classes involved in uploading files. These classes are the core classes of files uploaded by Apache components. The relevant knowledge about these core classes will be explained in detail in the following subsections.

Guess you like

Origin blog.51cto.com/15128443/2656570