场景:多图片时,下载成一个zip压缩包文件
代码实现:
1、安装 jszip 和 file-saver 插件
npm install jszip
npm install file-saver
2、引入并使用
import JSZip from "jszip";
import FileSaver from "file-saver";
/**
* 下载全部附件
* @param {*} fileList 下载列表
* @param {*} zipName 压缩包名称
*/
export function downloadMoreFileBtn(fileList, zipName) {
var zip = new JSZip();
var promises = [];
let cache = {};
for (let item of fileList) {
// item.feilePath为文件链接地址
// item.fileName为文件名称
if(item.imageUrl) {
const promise = getImgArrayBuffer(item.imageUrl).then((data) => {
// 下载文件, 并存成ArrayBuffer对象(blob)
zip.file(item.imageName, data, { binary: true }); // 逐个添加文件
cache[item.imageName] = data;
});
promises.push(promise);
} else {
// feilePath地址不存在时提示
alert(`附件${item.imageName}地址错误,下载失败`);
}
}
Promise.all(promises).then(() => {
zip.generateAsync({ type: "blob" }).then((content) => {
// 生成二进制流
FileSaver.saveAs(content, zipName); // 利用file-saver保存文件 zipName:自定义文件名
});
}).catch((res) => {
alert("文件压缩失败");
});
}
/**
* 文件以流的形式获取(参数url为文件链接地址)
* @param {*} url
* @returns
*/
export function getImgArrayBuffer(url) {
return new Promise((resolve, reject) => {
//通过请求获取文件blob格式
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.responseType = "blob";
xmlhttp.onload = function () {
if (xmlhttp.status == 200) {
resolve(xmlhttp.response);
} else {
reject(xmlhttp.response);
}
};
xmlhttp.send();
});
}
3、案例
import { downloadMoreFileBtn } from "@/utils/tools";
export default {
data() {
return {
basicImage: {
name: '使用功能基准图',
imageCount: 2,
imageList: [
{
imageName: '使用功能基准图1.jpg',
imageUrl: 'https://guoyan.haznet.cn/file/20230531100310f3u83t94wf.jpg',
},
{
imageName: '使用功能基准图2.jpg',
imageUrl: 'https://guoyan.haznet.cn/file/20230531100340aqer06tma5.jpg',
}
]
},
}
},
methods: {
/**
* 下载图片
*/
downloadImg(val) {
downloadMoreFileBtn(this.basicImage.imageList, this.basicImage.name)
},
},
}