Nodejs : download image from url

67 Views Asked by At

I have React.js and Node.js application. In that application I need to download image from URL like normal downloads which get stored in Download/specified path.

I have tried many methods from frontend (React) as well as backend (node.js by calling api to save image). Unfortunately most of solution opening image in new tab, some downloading file in unsupported format.

Some code tried in Node.js like below:

1.

router.post("/downloadImage", auth, async (req, res) => {
res.download('https://help.twitter.com/content/dam/help-twitter/brand/logo.png');
});
  1. router.post("/downloadImage", auth, async (req, res) => { res.attachment("https://help.twitter.com/content/dam/help-twitter/brand/logo.png"); });

with image-downloader library https://www.npmjs.com/package/image-downloader

router.post("/downloadImage", auth, async (req, res) => {
 try{
    const desktopDir = path.join(os.homedir(), "Downloads");
    console.log(desktopDir);
   
    const options = {
      url: 'https://help.twitter.com/content/dam/help-twitter/brand/logo.png',
      dest: 'C:\Users\Ganesh\Downloads"             // will be saved to /path/to/dest/image.jpg
    };

    download.image(options)
    .then(({ filename }) => {
      console.log('Saved to', filename); // saved to /path/to/dest/image.jpg
    })
    .catch((err) => console.error(err));
} catch (e) {
  console.log('error here',e);
  logger.error(e.message);
  res.send("error found");
}
  });

Above works for dest: 'C:\Users\Ganesh\Downloads' and gives 403 error for dest: ${desktopDir} . I am not able to figure it out how should I make dest dynamic for all device's Download folder with permission so it will get download.

Please help Thanks

0

There are 0 best solutions below