Add the yarn add Jszip dependency package
HTML module simple input and button
<template> <input type="file" multiple name="" id="" @change="fileChange"> <el-button @click="fileToZIP"> </template>Copy the code
Javascript module has two main parts file compression method fileToZIP
async fileToZIP() {
const that = this
// Create a jszip object
var zip = new JSZip()
// Create the filereader object
const reader = new FileReader()
// Create a promise object to return to await
const readFileAsync = file= > new Promise(resolve= > {
// The callback function of the filereader object, in which the read file object is added to the jszip object
reader.onload = () = > {
zip.file(file.name, file, { binary: true })
resolve()
}
// Read the object
reader.readAsBinaryString(file)
})
// Synchronize with await and wait for the promise to return before entering the next loop
for (let i = 0; i < this.fileList.length; i++) {
await readFileAsync(this.fileList[i])
}
The jszip object sets the compression parameters
zip.generateAsync({
// Compression type
type: "blob",
}).then(function (content) {
// Outputs the zip file stream
that.fileList = content
uploadFile(0)}); },Copy the code
The uploadFile() chunkSize parameter externally defines the slice size,
uploadFile(start) {
let end = (start + chunkSize > content.size) ? content.size : (start + chunkSize);
let formData = new FormData();
formData.set("file", this.fileList.slice(start, end));
uploadFile(formData).then(res=> {
console.log(res)
this.uploadFile(end)
})
}
Copy the code
Overall process:
1. Input Set fileList after uploading the file.
2. Click the upload button and invoke the fileToZIP method.
3. The fileToZIP method uses the JsZip library to export the bloB zip file stream. The uploadFile method is used to upload the bloB zip file stream, and the initial size is 0.
4. UploadFile cuts the file stream. The back end adds a file module to the file.