How to force the browser to download image files on click with JavaScript?

Spread the love

Sometimes, we want to force the browser to download image files on click with JavaScript.

In this article, we’ll look at how to force the browser to download image files on click with JavaScript.

How to force the browser to download image files on click with JavaScript?

To force the browser to download image files on click with JavaScript, we create a link.

For instance, we write

const link = document.createElement("a");
link.href = "images.jpg";
link.download = "Download.jpg";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

to call createElement to create a link.

Then we set its href property to the image URL.

We set its download property to the file name.

Then we call click to click the link to download the image.

Conclusion

To force the browser to download image files on click with JavaScript, we create a link.

Leave a Reply

Your email address will not be published. Required fields are marked *