vue批量文件打包压缩,包然后切片上传

1,254 阅读1分钟

添加yarn add jszip 依赖包

html模块简单的input和button

<template>
	<input type="file" multiple name="" id="" @change="fileChange">
    <el-button @click="fileToZIP">提交</el-button>
</template>

javascript模块主要两个部分 文件压缩方法fileToZIP

async fileToZIP() {
    const that = this
    //创建jszip对象
    var zip = new JSZip()
    //创建filereader对象
    const reader = new FileReader()
    //创建返回给await的promise对象
    const readFileAsync = file => new Promise(resolve => {
        //filereader对象的回调函数,在回调函数中,把读取的file对象添加到jszip对象中
        reader.onload = () => {
            zip.file(file.name, file, { binary: true })
            resolve()
        }
        //读取对象
        reader.readAsBinaryString(file)
    })
    //使用await实现同步效果,等待promise返回,再进入下一个循环
    for (let i = 0; i < this.fileList.length; i++) {
        await readFileAsync(this.fileList[i])
    }
    //jszip对象设置压缩参数
    zip.generateAsync({
        //压缩类型
        type: "blob",
    }).then(function (content) {
		//输出zip文件流
        that.fileList = content
        uploadFile(0)
    });
},

文件切片上传方法uploadFile() chunkSize参数在外部定义切片大小,

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)
    })
}

整体流程:

1.input上传文件后设置fileList。

2.点击上传按钮,调用fileToZIP方法.

3.fileToZIP方法对文件使用jszip库导出blob格式zip文件流调用uploadFile方法上传,传入初始大小0。

4.uploadFile进行文件流的切割,后端对文件添加文件模块,成功上传切片后再继续调用uploadFile上传第二个切片参数为end,直到文件传输完毕。