vue项目实现下载zip压缩包
作者:阿wei程序媛
这篇文章主要介绍了vue项目实现下载zip压缩包方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
vue项目下载zip压缩包
直接上代码
1.请求后端接口
//必须加上responseType,因为下载的zip属于流和普通的下载方式还是有较大区别的,同时headers也需要设置一下,不然是下载不了。
export function loadLabel(query) {
return request({
url: '/express/admin/loadLabel',
method: 'get',
params: query,
responseType: 'blob',
headers:{ 'Content-Type': 'application/json; application/octet-stream'},
})
}2.HTML
<el-button
size="mini"
type="text"
icon="el-icon-download"
@click="handleIndent(scope.row)"
v-hasPermi="['express:result:export']">
下载失败订单
</el-button>3.JS
//下载面单封装方法
fileHandle(data, fileName) {
let blob = new Blob([data], { type: 'application/zip' })
let url = window.URL.createObjectURL(blob)
const link = document.createElement('a') // 创建a标签
link.href = url
link.download = fileName // 重命名文件
link.click()
URL.revokeObjectURL(url) // 释放内存
},
/** 下载面单 */
handleSheet(row){
this.queryParams.parentId=row.id,
this.queryParams.statusCode=200
this.$confirm('是否确认下载成功的面单嘛?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
const loading1= this.$loading({
lock: true,
text: '正在下载,请稍等',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
});
loadLabel(this.queryParams).then(res => {
loading1.close();
this.fileHandle(res,'面单.zip')
})
}).catch(() => {
});
},当然也可以不用封装的方法
handleSheet(row){
this.queryParams.parentId=row.id,
this.queryParams.statusCode=200
const queryparmas=this.queryParams
this.$confirm("是否确认导出所有数据?", "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
}).then(function() {
return loadLabel(queryparmas);
}).then(response => {
let blob = new Blob([response.data], {type: 'application/zip'})
let url = window.URL.createObjectURL(blob)
const link = document.createElement('a') // 创建a标签
link.href = url
link.download = '面单.zip' // 重命名文件
link.click()
URL.revokeObjectURL(url) // 释放内存
}).catch(function(err) {
console.log(err)
});
},以上两种形式的代码就能实现zip下载
vue多文件下载zip格式
场景
多图片时,下载成一个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)
},
},
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
