Download Images from image url stored in array with javascript or best alternative
Solution 1:
Using the download
attribute of an anchor should do the trick...
EDIT
download only works for same-origin URLs, or the blob: and data: schemes. ref
Since this is not your case, you will have to create a blob with each image and fortunately, that is easy with the 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();
})
}
};
Tested on CodePen.