javascript// Function to download multiple images
function downloadImages(imageUrls) {
imageUrls.forEach((url, index) => {
// Create a temporary anchor element
const link = document.createElement('a');
link.href = url;
link.download = `image_${index + 1}.jpg`; // Change extension if necessary
document.body.appendChild(link);
link.click(); // Trigger download
document.body.removeChild(link); // Clean up
});
}
// Example usage
const images = [
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
'https://example.com/image3.jpg',
];
downloadImages(images);
Explanation:
Function Definition: The
downloadImages
function takes an array of image URLs as an argument.Creating Anchor Elements: For each image URL, a temporary anchor element (
<a>
) is created.Setting Attributes: The
href
attribute is set to the image URL, and thedownload
attribute specifies the filename for the downloaded image.Triggering Download: The anchor element is added to the document, clicked programmatically to trigger the download, and then removed from the document.
Notes:
- Make sure the images are accessible and have proper CORS headers if they are hosted on a different domain.
- Adjust the file extension in the
download
attribute if the images are of different types (e.g.,.png
,.gif
)
No comments:
Post a Comment