Download Images using JavaScript (Local and from URL)

avatar
Borislav Hadzhiev

Last updated: Mar 7, 2024
5 min

banner

# Table of Contents

  1. Download an image by using a simple link
  2. How to Download Images using JavaScript

# Download an image by using a simple link

If you need to download an image that is stored on the same domain or stored locally, you can use a simple a element that has the download attribute set.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div>bobbyhadz.com</div> <br /> <a href="house.png" download>Download image</a> </body> </html>
The code for this article is available on GitHub

The example above assumes that you have a house.png image located in the same directory as your index.html file.

download image by clicking on anchor tag

However, note that this approach only works when the href attribute of the a element points to:

  • a URL of an image that is hosted on the same domain, e.g. http://localhost:3000/house.png.
  • a local image, e.g. house.png.
index.html
<a href="house.png" download>Download image</a>

Make sure to specify the extension (e.g. .png).

If specifying a URL, make sure to include the protocol (http:// or https://).

You can also wrap the a element in a button and style it.

index.html
<button> <a href="house.png" download>Download image</a> </button>

The image is downloaded when the user clicks on the button.

The download attribute causes the browser to treat the linked URL as a download.

You can also set the download attribute to a string to specify the name the downloaded image should have on the user's file system.

index.html
<a href="house.png" download="my-file.png">Download image</a>

However, it is not guaranteed that the browser will use the specified image. Some browsers might use the name of the image as stored on your server's file system.

This approach wouldn't work if the image is hosted on a different domain.

In this case, you can use the fetch method as shown in the next subheading.

# How to Download Images using JavaScript

To download an image using JavaScript:

  1. Use the fetch() method to get a Blob object.
  2. Use the createObjectURL method to get a string containing the image's URL.
  3. Create an anchor element and use it to download the image.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> body { margin: 100px; } </style> </head> <body> <div>bobbyhadz.com</div> <br /> <button id="btn">Download image</button> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
async function downloadImage( imageSrc, nameOfDownload = 'my-image.png', ) { const response = await fetch(imageSrc); const blobImage = await response.blob(); const href = URL.createObjectURL(blobImage); const anchorElement = document.createElement('a'); anchorElement.href = href; anchorElement.download = nameOfDownload; document.body.appendChild(anchorElement); anchorElement.click(); document.body.removeChild(anchorElement); window.URL.revokeObjectURL(href); } const btn = document.getElementById('btn'); btn.addEventListener('click', () => { downloadImage( 'http://localhost:3000/house.png', 'my-image.png', ) .then(() => { console.log('The image has been downloaded'); }) .catch(err => { console.log('Error downloading image: ', err); }); });

javascript download image

The code for this article is available on GitHub

The downloadImage function takes care of downloading the image when the user clicks on the button element.

The function takes the source of the image and the name of the download as parameters.

The imageSrc parameter could be a complete URL that points to an image:

  • http://localhost:3000/house.png (make sure to specify the extension of the image as well)

Or it could be an image from the local file system, for example:

  • house.png
  • or images/house.png (a house.png image located in an images/ directory)
  • or ../images/house.png (an images/ folder that is located one directory up)
index.js
async function downloadImage( imageSrc, nameOfDownload = 'my-image.png', ) {}

The nameOfDownload parameter is used to set the name of the downloaded file on the user's file system.

index.js
async function downloadImage( imageSrc, nameOfDownload = 'my-image.png', ) { const response = await fetch(imageSrc); const blobImage = await response.blob(); const href = URL.createObjectURL(blobImage); const anchorElement = document.createElement('a'); anchorElement.href = href; anchorElement.download = nameOfDownload; document.body.appendChild(anchorElement); anchorElement.click(); document.body.removeChild(anchorElement); window.URL.revokeObjectURL(href); }
The code for this article is available on GitHub

The downloadImage function does the following things:

  1. It uses the built-in fetch() method to fetch the image from a URL (or from the local file system).
  2. It uses the blob() method of the Response object to get a Blob object (a file-like object of immutable, raw data).
  3. It uses the createObjectURL method to create an object URL that can be used to reference the contents of the image.
  4. It creates an a (anchor) element and sets its href attribute to the object URL and its download attribute to the name the downloaded image should have on the user's file system.
  5. It appends the anchor element to the body and simulates a click to initiate the download.
  6. It removes the link element from the body and revokes the URL after the image has been downloaded.

Make sure to update the parameters in the call to the function.

The example assumes that you are downloading a house.png image that is accessible at http:/localhost:3000/house.png.

You can either specify a complete URL to an image (including the protocol http:// or https://) and the extension (.png, .jpg, etc) or a path to a local image (e.g. house.png).

index.js
const btn = document.getElementById('btn'); btn.addEventListener('click', () => { downloadImage( 'http://localhost:3000/house.png', 'my-image.png', ) .then(() => { console.log('The image has been downloaded'); }) .catch(err => { console.log('Error downloading image: ', err); }); });
The code for this article is available on GitHub

If you try to download an image from a remote URL, the server that stores the image has to send CORS headers that allow your browser to download the image.

If you get a TypeError: Failed to fetch and CORS error, click on the link and follow the instructions.

CORS is a mechanism that allows a server to use a combination of HTTP headers to indicate from which domains, other than its own, it receives requests.

By default, a server can only be accessed from its own domain unless the correct Access-Control-Allow-* headers are set.

If you need to download a file or an image using axios, check out the following article.

I've also written an article on how to download a file in React.js.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.