This time I will show you how to implement file breakpoint resume transfer in H5, and what are the precautions for H5 file breakpoint resume transfer. The following is a practical case, let's take a look.
HTML5's FILE api has a slice method that can split BLOBPrinciple of resumable transmission
There are currently two commonly used methods of resuming transmission, one is through the websocket interface After all, the core content of resume uploading is to "slice" the file and then pass it to the server piece by piece. However, this seemingly simple upload process has countless pitfalls. The first is file identification. After a file is divided into several parts, how to tell the server how many pieces you have cut, and how the server should finally merge the files you uploaded, all need to be considered. So before the file starts to be uploaded, we need to have a "handshake" process with the server, tell the server the file information, and then agree on the size of the slice with the server. After reaching a consensus with the server, we can start subsequent files. Transmitted. The front end must pass each piece of file to the back end. After success, both the front end and the back end must be marked for subsequent breakpoints. When the file transfer is interrupted, the user can select the file again and use the logo to determine whether part of the file has been uploaded. If so, then we can continue to upload the file according to the last progress to achieve the function of resuming the upload. .Front-end slicing of files
With the HTML5 File api, cutting files is much simpler than imagined. Just use the slice methodvar packet = file.slice(start, end);
file.slice(0,1000); file.slice(1000,2000); file.slice(2000,3000); // ......
Upload of file fragments
In the previous part, we divided the file into several chunks through the slice method. The next thing to do is to transfer these fragments to the server. Here we use ajax'spost request to achieve
var xhr = new XMLHttpRequest(); var url = xxx // 文件上传的地址 可以包括文件的参数 如文件名称 分块数等以便后台处理 xhr.open('POST', url, true); xhr.onload = function (e){ // 判断文件是否上传成功,如果成功继续上传下一块,如果失败重试该快 } xhr.upload.onprogress = function(e){ // 选用 如果文件分块大小较大 可以通过该方法判断单片文件具体的上传进度 // e.loaded 该片文件上传了多少 // e.totalSize 该片文件的总共大小 } xhr.send(packet);
Detailed explanation of H5’s storage method,
How to use the constraint verification API in H5
The above is the detailed content of How to implement file breakpoint resume upload in H5. For more information, please follow other related articles on the PHP Chinese website!