大家好,我正在尝试下载我在 react 应用程序上显示的图像。该应用程序从 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;
}
};
最佳答案
使用 anchor 的 download
属性应该可以解决问题...
编辑
download only works for same-origin URLs, or the blob: and data: schemes. ref
由于这不是您的情况,因此您必须为每个图像创建一个 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 上测试.
关于javascript - 使用 javascript 或最佳替代方案从存储在数组中的图像 url 下载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70727517/