1. npm安装插件JSZip file-saver
2.封装组件
import JSZip from 'JSZip';
import { saveAs } from 'file-saver';
import axios from "axios";
/**
* 生成下载压缩包
* @param {Array} list
* @param {文件压缩包名} name
* @param {} fileType
*/
export default async function zipDownload(list, name, fileType) {
const zip = new JSZip();
for (let i = 0; i < list.length; i++) {
try {
const response = await axios.get(list[i], {
responseType: 'blob'
});
const blob = response.data;
zip.file(`${name}-${i + 1}.${fileType}`, blob);//文件名
} catch (err) {
console.error(err);
// 处理请求错误
}
}
const blob = await zip.generateAsync({ type: "blob" });
saveAs(blob, `${name}.zip`);//文件夹名
}
3.页面使用
import { getCropdetails } from "@/api/http";
import zipDownload from "@/utils/zipDownload";
import { prefix } from "@/api/base_url";
export default {
name: "Cropdetails",
data() {
return {
form: {},
topImages: [],
dialogVisible: false,
fileType:'jpg'
};
},
methods: {
async show(id) {
const { data } = await getCropdetails(id)
this.dialogVisible = true
this.form = data
this.form.s_pic = `${prefix}/${data.s_pic}`
this.topImages = data.pic_list.map(item => (`${prefix}` + item))
},
downImage() {
zipDownload(this.topImages,this.form.create_time,this.fileType)
},
}
};