Home > Net >  Download image from a third-party server button
Download image from a third-party server button

Time:01-18

In any browser, if you saw an image, you can right-click on it and click "save as" to download it.

I'm trying to make a button to download an image

enter image description here

The download button should download the image above, the barcode.

I am using react, not sure if this has something to do with the answers.

I read that you can use the <a/> tag with the download attribute, however, I'm on Firefox, and it's redirecting me to a page where the barcode image is hosted, and it's not opening the download window instead:

enter image description here

The code is pretty simple, it look as follows:

<a href='https://barcode.tec-it.com/barcode.ashx?data=${product.barcode}&code=&multiplebarcodes=true&backcolor=#ffffff&quietzone=10&quietunit=Px&size=Small' download>click me</a>

From the MDN docs:

download only works for same-origin URLs, or the blob: and data: schemes.

I want to implement this, how can I do it? I'm not the owner of the server where the image is hosted.

Can we do that in 2023?

The other questions are mixing between local images and images hosted on other servers. So I thought I could create this thread for people interested only in images on third party servers. - so we are all front-end here, no back-end related stuff.

CodePudding user response:

I think your question refers to this old question.

You need something on the server to send a Content-Disposition header to set the file as an attachment so the browser will not try to handle the file internally.

Please see: href image link download on click

CodePudding user response:

It only works on the same website, not an external link. Try an image of the same website. Ex: <a href="images/detailed-product.png" download>click</a>

CodePudding user response:

To do that, you can utilize the createObjectURL static method from URL to create download link for the image. Then, we create temporary <a> in a variable to open that link programmatically.

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

  const link = document.createElement('a')
  link.href = imageURL
  link.download = 'myimage.jpg'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
  • Related