implement large file upload and display progress information with JAVA
--- parsing the HTTP MultiPart Protocol
A . large File Upload basic description:
In various WEB frameworks, requests for browser uploads of files have their own processing objects responsible for parsing the contents of the Http MultiPart protocol and for developers to invoke the requested form content.
Like what:
The Spring framework uses similar Commonsmultipartfile objects to handle table binary file information.
While . NET uses the Htmlinputfile/httppostedfile object to process binary file information.
Pros: using framework built-in objects makes it easy to handle MultiPart binary Information requests from the browser, and protocol analysis operations do not involve developers.
Disadvantage: The process of receiving packets is completely enclosed in the framework's built-in objects, and the developer is not allowed to get the form and file contents from the interface until the processing (reception) of this request is complete. The progress information in the upload process cannot be accessed and cannot upload large size files (such as large file binary information of more than hundreds of megabytes).
Goal: We want to rely on the ability of the filter filter in the JAVA WEB Framework to implement a built-in object that does not rely on the framework, parsing from the browser request byte stream MultiPart Agreement to obtain all the information requested by this user, including multi-binary file information and other form item information. The size of the files uploaded by the user will not be restricted. And in the transmission process, we can get the current transmission progress information in real time.
Note: This article does not describe the ability of the. NET Framework to rely on the IHttpModule interface object to reach the Filter in the JAVA framework .
The final picture of this article is completed:
1.1 General Post Request protocol and MultiPart Protocol
General POST Request protocol, see figure:
Content-length the byte length of the request message content
The bottom red circle requests information for this form
MultiPart Request agreement, see figure:
Content-length is the content length byte of this request, this example 729366
Content-type for multipart/form-data, binary multi-segment form
Boundary is the delimiter for multi-segment form information, here is -----------------------------------7dflaxxxxxxxxxxx
The last piece of information,name= "File1", is the unit name of this file form,filename= "Untitled2.png" is the file name, Content-type:image/png for content area file format
The bottom of the red box is the binary information for the file.
From the above two graphs can be seen,MultiPart and ordinary POST on the structure of the agreement is significantly different, so our next job is to receive MultiPart by byte stream request the packet and analyze it.
1.2 Real-time access to current transfer progress information
Since we can get the request content area length from the above Http header, that is, the total bytes. Since we can receive packets from the browser in byte units from the Filter, we can also get the current received bytes in real time. So we can get the current percentage of transfer progress in real time, dividing the current received bytes by the received time to get the current transfer rate ( bytes / sec ).
This allows us to obtain the following transmission process information:
- Total bytes of this packet
- Number of bytes currently received
- This Request initiation time
- Current progress node time
- Current progress status (initial state, receiving data, receiving data, etc.)
Next, we only need to make progress id marking in Span style= "font-family: ' Times New Roman ';" >server end put java js access at a certain time interval server url id for identity, from server The public memory area gets the progress information for the current request. Once the information has been obtained, the progress bar can be operated in real time.
In the Java Framework, the public memory area is a ServletContext object (for example , using the SetAttribute method, The individual user progress information is stored in a HashMap object as a key-value pair. in the . NET Framework, the public memory area is a httpapplicationstate object.
Note: synchronous lock Control (synchronized) is required for write operations to the public memory area (HashMap object ) . Because the public memory area may produce a multi-user (multithreaded) concurrency behavior.
Two . problem Point Analysis:
2.1 segment Receive:
Because large files MultiPart packets in a single transmission, the number of bytes can be large (1G or more ), in order to obtain real-time progress information, As well as memory overhead control, we need to divide the receiving process into multi-segment processing, and the packet loop is received ( Example: Each loop receives only 64K data, while the current progress information is updated ).
2.2 full packet parsing? / partial data packets in real-time parsing ?
The common parsing protocol is to parse the packet after it has been received. These are implemented in two ways.
All packets are loaded into memory: this is a large amount of memory for large files MultiPart data ( e.g. a user is uploading 1G of data, The memory area must receive all 1G data before parsing, which is not available if a multi-user operation can cause a server crash .
The packet is written to the file and then loaded into memory: can only solve in the receiving process to open small memory and write fragmented files, when the data are written to the file, you also need to load into memory for the overall protocol analysis, but also burst caused by excessive memory overhead, causing the server crashes, this is not advisable.
We use a segmented receive, fragment parsing, the processing of a segmented write file. When the packet has been fully received, our entire analysis process is terminated, and the user uploads the file and other form information results. This allows us to complete the task with only a small memory area ( such as 64K) each time .
But this way will be faced with this receive the segmented information contains more than one form item information and the remaining incomplete form information, or the received fragment information does not actually contain any form information, is only a fragment of large file binary information. Therefore, this method will bring some complexity in coding.
Scenario 1:
Scenario 2:
Scenario 3:
Three . Source Parsing
Elements of the 3.1 project
This time we use the Spring Framework to achieve the "Large file transfer" function, the main design structure is as follows:
Filter object:
Filterthat is responsible for receiving MultiPart raw data to receive user requests before Spring built-in objects. It needs to be configured inWeb . xml , and the Filter starts when it is started and needs to be judged when the user requests come MultiPart whether the data information is legitimate, received and parsed.
Servletinputstream/bufferedinputstream object:
Using the above two objects, the request can be received by byte stream. In this case, a smaller receive buffer can be created, relying on Bufferedinputstream's read for a segmented loop reception.
GETBOUNDARYSECTFROMBUF () function:
Custom function, we need this function to parse the multiple form form information that may be contained in the fragment buffer, or part of the form information, or binary file fragment information. For form information analysis, populate the form data structure, which requires writing files for binary file information. This function needs to complete the important work of edge-receiving side parsing and writing files.
Progressinfo object:
A progress information class that describes the progress information for a single upload request. This object is used by the client to poll the request for progress information during the current transfer of the large file.
Formpart objects and listformpart Collections:
Formpart A description of a single form form. Listformpart describes the collection for all forms of this request. That is, all the table item contents that are called by subsequent code.
Controller layer getproginfo () handler function:
The function will accept the request for progress information from the browser and find the progress information object corresponding to the progesss ID from the current ServletContext public memory area Progressinfo, in XML returns the form to the browser. The function is polled by the client for the request.
multi-form.jsp page:
The display page of this form contains various form items (Input,Textarea,File , etc. ). This page will also show the progress bar, transmission status, transmission rate and other information used for this transmission. The progress information in the page will use JS to make periodic polling requests to the server to obtain and display.
upload-result.jsp page:
All the form item information used to display this request, including the normal Input form, and the File form information.
3.2 Key Module Analysis
3.2.1 Server side:
3.2.2 Browser side:
( This section can refer to the comments in the sample code )
Iv. . extensions and related
4.1 Breakpoint Continuation:
The
Commonly said breakpoint continuation refers to the file download of the breakpoint continued to pass. The use of http protocol Content-range keyword in Span style= "font-family: ' Times New Roman ';" >http header < span> Content-range property, sending subsequent file binary information to the browser. such as the network ant download software, that is, open multi-threaded use content-range
In the WEB , we use the Upload file breakpoint continuation function, mostly need to download ActiveX control to implement. That is equivalent to downloading an application locally, the file transfer protocol with the server does not use the HTTP Protocol, can be customized protocol completion.
The use of the existing HTTP Protocol to upload the file's breakpoint continues to be relatively small, it is said that the use of Ajax Slice method to separate local files into multiple the HTTP packet is post to the server, and the server needs to be received and consolidated to implement the package. The operation method is more complicated, I have not tried, have the interest of the friend can delve into.
4.2 key points to be perfected in this project:
Due to the haste of time, this project has only completed the main functions of large file upload and progress display. In the browser front-end progress information on the dynamic display, the front-end use of the JS framework (Ext JS, JQuery) and so on need more in-depth support.
On the server side, you can also rely on the filter configuration information, the file upload information to check or filter, such as can not upload some extension files, file upload size control, and save the file name uniqueness control, etc. also need more detailed description.
Attachment file list:
MultiData.txt: All MultiPart packet information intercepted at one time
MULTI-FORM.JSP: Multi-File upload Display page, including Get progress information JS script
upload_result.jsp: The form Item collection page for displaying upload results
Multiform.java: Main filter ,filter. Used to process all uploads.
Uploadproginfo.java: The Spring Bean Object of the Controller layer that is used to obtain the current progress information.
Note: Based on the global open source sharing concept, I will share more original and translation, so that more it people benefit from the progress together with you!
Gene Cloud Original, forwarding please indicate the source
[Email protected] (Busy work, something to send mail, QQ does not add, not to disturb, thank you!) )
year 6 months 2 days
"Original" in Java to achieve large file upload and display progress information