今天跟进一个线上bug,需求是看看哪些上传的图片是空的,步骤如下:
- 从埋点数据里面把图片名称摘出来
- 获取登陆态,将文件拼接成可获取图片的链接
- 将图片们下载下来
这里下载有个坑,就是请求间必须有时间间隔,不然一百多张图片只会触发十几次下载。 核心的代码就在这里了。
// 同页面内触发下载的方法
const downloadImage = (imageUrl, name) => { //
fetch(imageUrl, {
method: 'get',
mode: 'cors',
})
.then((response) => response.blob())
.then((data) => {
const downloadUrl = window.URL.createObjectURL(new Blob([data]));
const link = document.createElement('a');
link.href = downloadUrl;
link.setAttribute('download', `${name}.jpeg`);
document.body.appendChild(link);
link.click();
link.remove();
})
.catch(e => {
console.log('wrong fetch', e)
});
};
let i = 1
function downloadSequentially() {
// 不延时一下,一百多条链接只能下到十几条
setTimeout(() => {
const url = imgUrl.pop()
console.log('i, url', i, url, imgUrl.length)
downloadImage(url, i++)
if (imgUrl.length) downloadSequentially()
}, 500)
}
setTimeout(() => {
// 域名是https的,只能下载https的,神奇规矩
window.imgUrl = window.imgUrl.map(url => url.replace('http', 'https'))
console.log('window.imgUrl', window.imgUrl)
downloadSequentially()
}, 5000)