3

I have an application that displays a photo gallery. Under each photo there is a button which, when clicked, is supposed to save the photo on the user's computer. Unfortunately, the photos are saved as an HTML document when downloaded. That is why they cannot be opened after downloading. The photos are stored in a static uploads folder attached to the project using nodejs. How do I download a photo so that it is saved in the correct format?

What I have already tried is using the download attribute by placing the photo under the a tag as here:

<a href={file.path} download>download</a>` or `<a href={file.path} download={file.name}>download</a>.

I also tried using the file-saver module, but with no positive result. With this solution, the image is also saved as an HTML documen:

const Gallery = () => {
//
const downloadImage = (file) => {
  saveAs(
    `http://localhost:3000${file.path}`,
     file.name + '.' + file.type
   )
}

//

  return (
    <button onClick={downloadImage(currentFile)} type='button'> download </button>
  )
}

In react-router-dom, I don't have the route set so that I can preview the photo directly after clicking on the photo.

nsog8sm43x
  • 329
  • 5
  • 14

1 Answers1

2

i think this can help you, call download function then pass image url,image name after download and type of image

function toDataURL(url) {
  return fetch(url)
    .then((response) => {
      return response.blob();
    })
    .then((blob) => {
      return URL.createObjectURL(blob);
    });
}

async function download(url, name = "download", type = "png") {
  const a = document.createElement("a");
  a.style.display = "none";
  a.href = await toDataURL(url);
  a.download = name + "." + type;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

The code above is adapted from this answer by @Emeric.

code description

first create temporary link (invisible) and then send request to your server to fetch image data, then set image data as link href that we created and then add link to body, we need virtual click on this link using js finally remove a tag from body

Done, image downloaded...

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Mohammad
  • 29
  • 6