用js封装的本地下载方法
一、应用场景
- 如:将页面的图片保存到本地,或者视频、压缩包等其他文件
代码:
downloadZip(fn, name) {
console.log("DirectDownloadFn")
const a = document.createElement('a')
// let url = baseUrl + binding.value // 若是不完整的url则需要拼接baseURL
const url = fn // 完整的url则直接使用
// 这里是将url转成blob地址,
fetch(url).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
a.href = URL.createObjectURL(blob)
// //console.log(a.href)
if (name) {
a.download = name; // 下载文件的名字
} else {
a.download = Math.floor(Math.random() * (1000 - 1)) + 1 || '' // 下载文件的名字
}
document.body.appendChild(a)
a.click()
//在资源下载完成后 清除 占用的缓存资源
window.URL.revokeObjectURL(a.href);
document.body.removeChild(a);
})
},
- 调用方法
//拿vue项目来演示:
this.downloadZip(参数1, 参数2);
//参数1: 图片的url路径
//参数2: 想要保存的文件名称,这个是自己定,可以随意
//完整写法
const url = "https://baike.baidu.com/link?url=36g2berhfOdjHCaPDTqi_bGYSAX2B2qnCi1jzlnpqTm5VPN_YMNpgUYOdQv30KqxgIU3CCNnnOBbHrt0_tHwgqeJ3-iJPOwLCuBFnyjUpcC"
this.downloadZip(url, "ikun");
二、 多张图片下载(扩展)
- 代码:
downloadImages(urls, names = []) {
console.log("DirectDownloadFn", urls);
urls.forEach((url, index) => {
let that = this
const a = document.createElement('a');
// Fetch each image and convert it to a blob
fetch(url).then(res => res.blob()).then(blob => {
a.href = URL.createObjectURL(blob);
// Use the provided name or generate a random name
const name = that.contentInfoObj.type_name + '_' + (index + 1) || Math.floor(Math
.random() * (1000 - 1)) + 1;
a.download = name;
document.body.appendChild(a);
a.click();
// Clean up
window.URL.revokeObjectURL(a.href);
document.body.removeChild(a);
}).catch(error => {
console.error(`Failed to download image from ${url}:`, error);
});
});
},
- 方法调用
this.downloadImages(参数1, 参数2)
//说明: 两个参数都是数组
//参数1: 图片路径数组
//参数2: 名称数组