单图片下载
//使用
download('https://img1.baidu.com/it/u=1493209339,2544178769&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1715101200&t=854f3434686cfd2cba9d6a528597d15c')
//下载逻辑
const download = async (modelUrl) => {
const response = await fetch(modelUrl);
// 将响应体转换为Blob
const blob = await response.blob();
// 创建隐藏的a标签来触发下载
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'image.jpg'; // 自定义下载的文件名
link.click();
document.body.removeChild(link); // 下载后移除元素
}
多图片打包下载
安装yarn add jszip
或 npm i jszip
yarn add file-saver
或 npm i file-saver
import JSZip from "jszip"
import { saveAs } from 'file-saver'
const imgList = ref([{ id: 1, url: 'https://img1.baidu.com/it/u=1493209339,2544178769&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1715101200&t=854f3434686cfd2cba9d6a528597d15c' }, { id: 2, url: 'https://img1.baidu.com/it/u=3714509592,1056938510&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1715101200&t=855f002cda64244524d6945999b0be2a' }])
const downloadImg = async () => {
const imageUrls = []; // 替换为实际的图片URL数组
const filenames = []; // 对应的文件名数组
arr.forEach(ii => {
imageUrls.push(ii.url)
filenames.push((ii.name || ii.id) + '.png')
})
createAndDownloadImageZip(imageUrls, filenames);
}
//
async function createAndDownloadImageZip(images, filenames) {
console.log(images)
const zip = new JSZip();
for (let i = 0; i < images.length; i++) {
// 获取图片资源
fetch(images[i])
.then(response => response.blob())
.then(blob => {
// 将Blob添加到ZIP包中,这里假设图片名为'image'+i+'.jpg'
zip.file(`img${i}.jpg`, blob);
// 在所有图片都处理完之后生成ZIP
if (i === images.length - 1) {
zip.generateAsync({ type: 'blob' }).then(content => {
// 下载ZIP文件
saveAs(content, 'downloaded_images.zip');
});
}
});
}
}