前端文件批量下载并打包成压缩文件

前端 2021-10-08 2217

实现下载打包并压缩,需要引入2个文件

npm install jszip --save // 打包文件
npm install file-saver --save // 是在客户端保存文件的解决方案

以一个组件来讲解,点击按钮批量下载文件并打包文件

下载文件请求

// 下载文件
export function downloadFile (url) {
    return new Promise((resolve, reject) => {
        axios({
            method:'get',
            url,
            responseType: 'blob'
        }).then(data => {
            resolve(data.data)
        }).catch(error => {
            reject(error.toString())
        })
    })
}
<template>
    <el-button type="primary"
               style="float: right"
               :loading="btnLoading"
               @click="handleDownload">批量下载
    </el-button>
</template>

<script>
import {downloadFile} from "api/static";
import JSZip from "jszip";
import FileSaver from "file-saver";

export default {
    name: "BatchDownloadBtn",
    props: {
        batchStyle: {
            type: Object
        },
        urls: { // 打包文件的数据包括下载地址
            type: Array
        },
        zipFileName: { // 打包文件名称
            type: String,
            default: 'zipFile'
        }
    },
    data() {
        return {
            btnLoading: false
        }
    },
    methods: {
        handleDownload() {
            this.btnLoading = true;
            const zip = new JSZip();
            const cache = {};
            const promises = [];
            this.urls.forEach((value, index) => { // 遍历需要打包的文件
                const promise = downloadFile(value).then(data => { // 下载文件
                    const arr_name = value.split("/");
                    const file_name = arr_name[arr_name.length - 1]; // 获取文件名
                    zip.file(file_name, data, {binary: true}); // 逐个添加文件
                    cache[file_name] = data;
                }).catch(() => {
                    this.btnLoading = false;
                })
                promises.push(promise);
            })
            Promise.all(promises).then(() => {
                zip.generateAsync({type: "blob"}).then(content => {
                    // 生成二进制流
                    FileSaver.saveAs(content, `${this.zipFileName}.zip`); // 利用file-saver保存文件  自定义文件名
                    setTimeout(() => {
                        this.$message.success('附件下载成功!');
                        this.btnLoading = false;
                    }, 2000)
                });
            }).catch(() => {
                this.btnLoading = false;
            });
        }
    }
}
</script>

<style scoped>

</style>

 

标签:前端

文章评论

评论列表

已有0条评论