1、前端展示效果
2、前端代码
第一步:安装jszip 、file-saver
cnpm install jszip
cnpm install file-saver
第二步:导入jszip 、file-saver
import JSZip from 'jszip'
import FileSaver from "file-saver"
第三步:展示代码
<!--查看照片-->
<el-dialog title="查看照片" :visible.sync="watchPohotVisible" width="40%" :close-on-click-modal="false">
<div align="right">
<el-button icon="el-icon-download" type="primary" @click="downImg">图片下载</el-button>
</div>
<div>
<el-form>
<el-form-item>
<div style="width: 100%;margin-top: 40px;" v-if="galleryRefresh">
<div
class="image"
v-for="(image, imageIndex) in images"
:key="imageIndex"
@click="index = imageIndex"
:style="{ backgroundImage: 'url(' + image.thumbnail + ')', width: '200px', height: '200px'}"
>
</div>
</div>
</el-form-item>
</el-form>
</div>
</el-dialog>
第四步:下载方法
//通过url 转为blob格式的数据
getImgArrayBuffer(url){
let _this=this;
return new Promise((resolve, reject) => {
//通过请求获取文件blob格式
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.responseType = "blob";
xmlhttp.onload = function () {
if (this.status == 200) {
resolve(this.response);
}else{
reject(this.status);
}
};
xmlhttp.send();
});
},
// imgDataUrl 数据的url数组
downImg() {
let _this = this;
let zip = new JSZip();
let cache = {};
let promises = [];
_this.title = '正在加载压缩文件';
for (let item of this.images) {
const promise= _this.getImgArrayBuffer(item.href).then(data => {
// 下载文件, 并存成ArrayBuffer对象(blob)
zip.file(item.title, data, { binary: true }); // 逐个添加文件
cache[item.title] = data;
});
promises.push(promise);
}
Promise.all(promises).then(() => {
zip.generateAsync({ type: "blob" }).then(content => {
_this.title = '正在压缩';
// 生成二进制流
FileSaver.saveAs(content, '照片'); // 利用file-saver保存文件 自定义文件名
_this.title = '压缩完成';
});
}).catch(res=>{
_this.$message.error('文件压缩失败');
});
},