Categories
JavaScript Answers

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

Spread the love

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

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

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

To force browser to download image files on click with JavaScript, we set the download property of the 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 create the link with createElement.

Then we set the download property to the file name of the downloaded file.

Finally, we call click to click on the link to download the file.

Conclusion

To force browser to download image files on click with JavaScript, we set the download property of the link.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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