vue前端根据url批量下载图片

本文介绍了一个使用 Vue.js 实现的批量下载图片并将其压缩为 ZIP 文件的方法。通过集成 jszip 和 file-saver 库,实现了从服务器获取图片二进制数据、创建 ZIP 文件并保存到客户端的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装依赖

npm install jszip
npm install file-saver

代码
// import
import JSZip from'jszip'
import FileSaver from'file-saver'

// html
<el-button type="primary" :loading="download" @click="down">批量下载</el-button>
<span v-if="download">{{ title }}:{{ ok }} / {{ all }}</span>

// data
data() {
	return {
	  imgList: [],
	  download: false,
      ok: 0,
      all: '',
      title: '正在加载压缩文件',
	}
}

// methods
down() {
  this.all = this.imgList.length 
  this.download = true
  this.Download(this.imgList)
},

getImgListBuffer(url){
  return new Promise((resolve, reject) => {
    let xmlhttp = new XMLHttpRequest()
    xmlhttp.open("GET", '/static' + url, true)
    xmlhttp.responseType = "blob"
    xmlhttp.onload = function () {
      if (this.status == 200) {
        resolve(this.response)
      }else{
        resolve(this.response)
      }
    }
    xmlhttp.send();
  })
},

Download(imgDataUrl){
  let zip = new JSZip()
  let cache = {}
  let promises = []
  for (let item of imgDataUrl) {
    const i = item.slice(25)
    const promise= this.getImgListBuffer(i).then(data => {
      zip.file(item, data, { binary: true })
      cache[item] = data
      this.ok++ // 记录加载图片数
    });
    promises.push(promise)
  }
  Promise.all(promises).then(() => {
    this.title = '正在压缩'
    zip.generateAsync({ type: "blob" }).then(content => {
      FileSaver.saveAs(content, this.value) // 自定义文件名
      this.$message.success('压缩完成')
      this.download = false
      this.ok = 0
    });
  }).catch(res=>{
    this.$message.error('文件压缩失败')
    this.download = false
    this.ok = 0
  })
},
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值