我正在尝试下载我在反应应用程序上显示的图像。该应用程序从 API 获取图像并将其显示在网页上,并将 img src 存储在数组中。我正在尝试制作一个下载按钮,它将循环遍历我的 src 数组并下载显示的所有图像,并且需要一些指导。我读过很多以前的帖子,并意识到我无法在我的 React 应用程序中使用 cURL,并且 fetch API 无法下载图像。我想看看是否有办法用 JavaScript 来做到这一点,或者是否有其他编程语言的简单替代方案。
const downloadAll = () => {
const imgArr = document.querySelectorAll('img');
for (let i = 0; i < imgArr.length; i++) {
let a = imgArr[i].src;
}
};
使用锚点的
download
属性应该可以解决问题......
编辑
download 仅适用于同源 URL,或 blob: 和 data: 方案。 参考
由于这不是您的情况,因此您必须为每个图像创建一个 blob,幸运的是,使用
fetch
API 可以轻松实现这一点。
const downloadAll = async () => {
// Create and append a link
let link = document.createElement("a");
document.documentElement.append(link);
const imgArr = document.querySelectorAll("img");
for (let i = 0; i < imgArr.length; i++) {
await fetch(imgArr[i].src)
.then(res => res.blob()) // Gets the response and returns it as a blob
.then(blob => {
let objectURL = URL.createObjectURL(blob);
// Set the download name and href
link.setAttribute("download", `image_${i}.jpg`);
link.href = objectURL;
// Auto click the link
link.click();
})
}
};
在 CodePen 上测试。
这是我的答案:
const urls = ['imgUrl1', 'imgUrl2', ....]
const fetchFile = async function(url) {
const resp = await fetch(url)
return resp.blob()
}
const exportFile = async function(file) {
let a = document.createElement('a');
a.href = await URL.createObjectURL(file);
a.setAttribute('download', '');
a.click();
}
let index = 0
while (index < 10000000) {
const file = await fetchFile(urls[index])
exportFile(file)
index++
}
走吧!