This is the second day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021

In VUE, file fragment uploading is realized. The idea of fragment uploading is to save the unique identifier of the file after getting the file, cut the file, and upload the file in sections, uploading one section at a time, judging the uploading progress according to the unique identifier until all the fragments of the file are uploaded.

Slice method of file object

1. File object properties

  1. Size indicates the size of the binary object
  2. Type Indicates the type of the binary object
  3. The slice method splits files

2. File. Slice (startByte,endByte)

  1. The first parameter startByte indicates that the file begins to read Byte bytes
  2. The second argument is the end read byte

Two: File upload

1. File slice definition

// The file slice size is set to 1MB
    let idx = 1;
    const bytesPerPiece = 1 * 1024 * 1024;
    let startBytes = idx * bytesPerPiece;
    let endBytes = startBytes + bytesPerPiece;
    if (endBytes > file.size) {
        endBytes = file.size;
    }
Copy the code

2. Cut files

// Slice method of file object, core method of file fragmentation
    const chunk = file.slice(startBytes, endBytes);
Copy the code

3. Define the Form object

// Define the form object
    let params = new FormData();
    params.set("chunk", idx);
    params.set("chunks", totalPieces);
    params.set("size", file.size);
    params.set("name", file.name);
    params.set("plupload", chunk);
Copy the code

4. Request the background

PostForm is a custom form request method
    postForm('url', params).then((res) = > {
        // Depending on whether the back end returns complete
        if (true) {
            return res;
        }
        // Upload recursively
        this._uploadBig(file, ++idx);
    })
Copy the code

5. All codes

/** * @param {Object} file * @param {Number} idx current fragment * @return {Object} */ uploadBig(file, Const bytesPerPiece = 1 * 1024 * 1024; let startBytes = idx * bytesPerPiece; let endBytes = startBytes + bytesPerPiece; if (endBytes > file.size) { endBytes = file.size; } const totalPieces = math.ceil (file.size/bytesPerPiece) // Exit if(startBytes > = file.size) { return false; } const chunk = file.slice(startBytes, endBytes); Let params = new FormData(); params.set("chunk", idx); params.set("chunks", totalPieces); params.set("size", file.size); params.set("name", file.name); params.set("plupload", chunk); PostForm ('url', params). Then ((res) => {if (true) {return res; } // Upload this._uploadBig(file, ++idx); })}Copy the code

Above is the file fragment upload all the code, record, review the old know new!