Notes on resuming transfer at breakpoints at both the front and rear ends

principle

Regarding resumable downloading, everyone should have been exposed to it. For example, if the download is paused, the download can be continued the next time you click Start. If there is no resumable download, then just stop for a moment, then you will hear everything, and the download will start again next time. .
In principle (take uploading as an example), it is to upload a file into multiple parts (slices), then record which slice it is uploaded to, and continue to upload the last paused slice next time. When all slices are uploaded, Merge all files.

Front-end slicing code

The file can be sliced ​​by size or number of copies. The following code is for slicing by size. The md5 value is the unique identifier of the file. It can also be uploaded in seconds
based on the md5 value of the file (each upload, verify the md5 value, if in the database If this value is present, it is the same file, just copy the database file address, no need to upload it repeatedly)

import axios from "axios";
import SparkMD5 from 'spark-md5'

const upload = {
    
    
    uploadFile(file, chunkSize, url) {
    
    
        const fileReader = new FileReader();
        const spark = new SparkMD5.ArrayBuffer()
        fileReader.readAsArrayBuffer(file)
        fileReader.onload = async function (e) {
    
    
            spark.append(e.target.result)
            const md5 = spark.end();
            let uploadedSize = 0;
            const fileSize = file.size;
            // 向上取整
            const totalChunks = Math.ceil(fileSize / chunkSize);
            while (uploadedSize < fileSize) {
    
    
                // 因为最后一次可能会超出文件总大小,所以取文件总大小
                const endSlice = Math.min(uploadedSize + chunkSize, fileSize);
                const blob = file.slice(uploadedSize, endSlice);
                const formData = new FormData();
                formData.append('file', blob);
                formData.append('start', uploadedSize);
                formData.append('end', endSlice);
                formData.append('totalChunks', totalChunks);
                formData.append('md5', md5);
                const data = {
    
    };
                formData.forEach((value, key) => data[key] = value);
                console.log(data)
                const response = await axios.post(url, formData, {
    
    
                    headers: {
    
    
                        'Content-Type': 'multipart/form-data'
                    }
                });
                if (response.data.code === 200) {
    
    

                } else {
    
    
                    throw new Error("");
                }
            }
        }


    }
}

export default upload;

Backend receiving code

. . . Will make up for it in a second

Guess you like

Origin blog.csdn.net/jl15988/article/details/131939354