DEV Community

Cover image for Download Images using JavaScript πŸ“Έ
Sapan Bodiwala
Sapan Bodiwala

Posted on

74 7

Download Images using JavaScript πŸ“Έ

Let's say you're trying to add a feature to your site or app to allow users to download an image upon clicking a button. Should be pretty straight forward right? I thought so myself as I needed to add this feature when building an internal media library tool at Discovery.

I tried adding this feature by just adding the download attribute to an anchor tag and setting the href attribute to the image url (cross-origin url).

<a href='URL_HERE' download>Download image</a>
Enter fullscreen mode Exit fullscreen mode

Turns out that Chrome started ignoring download attributes that pointed to cross origin urls.

To solve this, we'll take advantage of the browser built in fetch method. You'll need to add an event listener to the element that you want to trigger the image download and call the below function:

// Using fetch
async function downloadImage(imageSrc) {
  const image = await fetch(imageSrc)
  const imageBlog = await image.blob()
  const imageURL = URL.createObjectURL(imageBlog)

  const link = document.createElement('a')
  link.href = imageURL
  link.download = 'image file name here'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
Enter fullscreen mode Exit fullscreen mode

The imageSrc function parameter represents the cross origin image url.

  1. First, we use fetch to get the ReadableStream data of the image
  2. Next, we call the blob method provided by fetch to get the raw image data
  3. Third, we use the URL Web API to call the createObjectURL static method to create a URL that represents the image's download URL
  4. Finally, an anchor element is created to set the new url to the href attribute. You can also set the name of the file by setting the download attribute of the anchor element. Last, we append the anchor element we created to the DOM and trigger a click to download the image and then quickly remove the anchor from the document.

And there you go! You now have the ability to download images on the trigger of a function!

I hope this helped and was useful for you!

This post can also be found at sapanbodiwala.com/blog

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (15)

Collapse
 
vishwakarmad1999 profile image
Divya Vishwakarma β€’

Mota bhai this doesn't work when there's CORS restriction!!!
It will fail at the first fetch call itself.

Collapse
 
semleel profile image
Yi Sem β€’

it works!! thanks alot

Collapse
 
akashkaintura profile image
AKASH KAINTURA β€’

Not Helpful

Collapse
 
san profile image
Ihsan β€’

Thanks dude!

Collapse
 
amirjafari1992 profile image
Amir Jafari β€’

You made my day man! Thank you for sharing

Collapse
 
daddasoft profile image
Dadda Hicham β€’

best one thanks πŸ‘

Collapse
 
uzair004 profile image
Muhammad Uzair β€’

What if image can't be fetched from its source ? it there any other way to get image from DOM ?

Collapse
 
woochul profile image
Woochul Lee β€’

It works well. Thanks.

Collapse
 
faisalamin001 profile image
Faisal Amin β€’

Awesome, it worked! πŸ‘

Collapse
 
javicodev11 profile image
Javico11 β€’

Maybe someone solved the CORS problem?

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started β†’

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay