1.npm install jszip --save / yarn add jszip -S
2.npm install file-saver --save / yarn add file-saver -S
3.yarn add axios
以下为完整代码
<template> <div class="hello"> <div> <Button @click='downLoad'>批量打包下载文件</Button> </div> </div> </template> <script> import JSZip from 'jszip' import FileSaver from 'file-saver' import axios from 'axios'; export default { name: 'HelloWorld', props: { msg: String }, data() { return { } }, methods: { getFile(url) { return new Promise((resolve, reject) => { axios({ method: "get", url, responseType: "blob" }).then(data => { resolve(data.data); }).catch(error => { reject(error.toString()); }); }); }, downLoad() { const data = ["url1","url2"]; // 需要下载打包的路径, 可以是本地相对路径, 也可以是跨域的全路径 const zip = new JSZip(); const cache = {}; const promises = []; data.forEach(item => { const promise = this.getFile(item).then(data => { // 下载文件, 并存成ArrayBuffer对象 const arr_name = item.split("/"); const file_name = arr_name[arr_name.length - 1]; // 获取文件名 zip.file(file_name, data, { binary: true }); // 逐个添加文件 cache[file_name] = data; }); promises.push(promise); }); Promise.all(promises).then(() => { zip.generateAsync({ type: "blob", compression: 'DEFLATE', // STORE: 默认不压缩, DEFLATE:需要压缩 compressionOptions: { level: 9 // 压缩等级 1~9 1 压缩速度最快, 9 最优压缩方式 } }).then(content => { // 生成二进制流 FileSaver.saveAs(content, "RobotInformation.zip"); // 利用file-saver保存文件 自定义文件名 }); }); } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> h3 { margin: 40px 0 0; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style>
标签:vue,const,name,zip,压缩,js,file,data From: https://www.cnblogs.com/yn-cn/p/17098605.html