Search code examples
javascriptnode.jsamazon-web-servicesexpressaws-sdk-js

cant view image that I downloaded using aws-sdk and wrote to disk using node


Im downloading an image (.png file) on my express server from an s3 bucket using the aws-sdk for node and then writing it to the disk using fs.writeFileSync. the problem is when I try to view the image on my computer, it says: is appears that we dont support this file format. I checked properties of the downloaded images and its 37.2 KB so it means something was returned.

Is this not the correct way to download the image?

here is my code:

function downloadFile(fileKey) {
  const downloadParams = {
    Key: fileKey,
    Bucket: bucketName,
  };
  return s3.getObject(downloadParams).promise();
}


router.get("/getImage", async (req, res) => {
  try {
    let image= await downloadFile(`${req.query.imageID}.png`);
    fs.writeFileSync(`Images/${req.query.image}.png`, image);

    res.status(200).send();
  } catch (e) {
    console.log(e);
    res.status(500).send(e);
  }
});





Solution

  • My mistake was that I writing the full s3 result to the disk(image) and not the Body from the result. this is the correct code:

     fs.writeFileSync(`Images/${req.query.taskID}-plot.png`, image.Body);