HTML
<el-button class="text-button" type="text" @click="handleBatchdownload(scope.row)">下载文件</el-button>
JS:
1. 方法一,用jszip和file-saver第三方包,打包成 zip 下载
npm install jszip
npm install file-saver
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
handleBatchdownload(data) {
this.$confirm('确定下载所有文件?', '下载确认', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.batchDownload(data.downloadUrl.split(',')); // 方法一,用jszip和file-saver第三方包
}).catch(() => {})
},
batchDownload(data) {
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 => {
saveAs(content, "zly.zip"); // *生成二进制流,利用file-saver保存文件,文件名自定义
});
});
},
getFile(url) {
return new Promise((resolve, reject) => {
axios({
method: "get",
url,
responseType: "blob"
}).then(data => {
resolve(data.data);
}).catch(error => {
reject(error.toString());
});
});
}
2. 方法二,用 a 标签做,但是需要允许弹出弹窗
downloadByA(url, fileName) {
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = fileName;
a.setAttribute('target', '_blank')
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}