Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

302
Views
How to save an image and download it in ReactJS?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
}

code source => https://stackoverflow.com/a/56041886/11115457

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...

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!