vue 本地圖片批量下載以及壓縮成zip檔案下載
阿新 • • 發佈:2021-06-18
// 資料初始化
selectedRows = [{ id: '1212313', name: '1號', qrcodeUrl: '"http://duoduoping-qiniu.landdt.cn/16239812769941405433547020722178.jpg"' }, { id: '1212314', name: '2號', qrcodeUrl: '"http://duoduoping-qiniu.landdt.cn/16239812769941405433547020722178.jpg"' }]
一、 批量下載圖片
圖片直接下載,利用迴圈a標籤進行檔案下載。(這樣是圖片一個一個進行下載)
batchQrCodeLocal () { if (this.selectedRows.length === 0) { this.$notification.warning({ message: '請先勾選下載資料!' }) return } for (let i = 0; i < this.selectedRows.length; i++) { axios.post(this.selectedRows[i].qrcodeUrl, {}, { responseType:'blob' // 設定響應的資料型別為一個包含二進位制資料的 Blob 物件,必須設定!!! }).then(res => { console.log(res) const mimeType = 'image/png' const aLink = document.createElement('a') var blob = new Blob([res.data], { type: mimeType }) aLink.style.display = 'none' aLink.setAttribute('href', URL.createObjectURL(blob)) aLink.setAttribute('target', '_blank') aLink.setAttribute('download', this.selectedRows[i].name + this.selectedRows[i].id) // 設定下載檔名稱 document.body.appendChild(aLink) aLink.click() document.body.removeChild(aLink) window.URL.revokeObjectURL(aLink.href) }) } },
二、圖片批量處理成壓縮包後進行下載zip檔案
下載圖片檔案後存進zip,然後生成二進位制流,利用file-saver儲存檔案。
// 需要的依賴包 import axios from 'axios' import FileSaver from 'file-saver' import JSZip from 'jszip'
// methods getFile (url) { return new Promise((resolve, reject) => { axios({ method: 'get', url, responseType: 'blob' }).then(response => { resolve(response.data) }).catch(error => { reject(error.toString()) }) }) }, batchQrCodeZip () { if (this.selectedRows.length === 0) { this.$notification.warning({ message: '請先勾選下載資料!' }) return } this.exportLoading = true const zip = new JSZip() const _this = this const promises = [] const cache = {} for (const item of this.selectedRows) { const promise = _this.getFile(item.qrcodeUrl).then(data => { // 下載檔案, 並存成ArrayBuffer物件 // const file_name = item.realName // 獲取檔名 zip.file(item.realName + '.png', data, { binary: true }) // 逐個新增檔案,需要加字尾".png" cache[item.realName] = data }) promises.push(promise) } Promise.all(promises).then(() => { zip.generateAsync({ type: 'blob' }).then(content => { // 生成二進位制流 FileSaver.saveAs(content, '人員二維碼') // 利用file-saver儲存檔案 自定義檔名 _this.$notification.success({ message: '下載完成!' }) }) _this.exportLoading = false }).catch(res => { _this.$notification.warning({ message: '檔案下載失敗!' }) _this.exportLoading = false }) },