0

I am trying to download an image to the client in my little node app. Here is my code:

app.post("/image-download", (req, res, next) => {
  const image = path.join(__dirname, "/images", `/${req.body.imageName}`);
  res.setHeader("Content-Type", "image/jpeg");
  res.setHeader("Content-Disposition", "attachment");
  res.send(image);
});

Where this image is stored in the path that I am constructing. I using fetch API on the front end and am able to receive the image and log it to the console, but how can I download it? Is this something that needs to be done on the front end? Thanks for the help!!

Edit: Just to clarify, what I want to mimic is the unsplash.com functionality. I want users to be able to download the images and this is my download route for their selected image.

NickLans
  • 67
  • 1
  • 11
  • Do you want to download it with the console or a download button in the frontend? – Arjen Feb 17 '21 at 20:46
  • Maybe you can try this answer? https://stackoverflow.com/questions/12740659/downloading-images-with-node-js – Arjen Feb 17 '21 at 20:48
  • I want to download it so the client can save the file to their local drive – NickLans Feb 17 '21 at 21:13
  • @ARVOCI that example downloads the image to the local machine (I believe), I want to send the image to the client so they can download it locally (similar to unsplash.com) – NickLans Feb 18 '21 at 07:26

1 Answers1

0

You can use res.download: http://expressjs.com/en/api.html#res.download

app.post("/image-download", (req, res, next) => {
  const image = path.join(__dirname, "/images", `/${req.body.imageName}`);
  res.download(image);
});

By the way, it's cleaner to use the GET method, because you don't create an entity but return one.

Naor Levi
  • 1,713
  • 1
  • 13
  • 27
  • Hi Naor thanks for the reply! I tried this as well and it doesnt work, at lease out of the box. Is there something special I should do on the front end? I am using the fetch API, would I need to start the download from the client side? Also thanks for the note on GET, maybe its better to put the image name as a query param instead of in the body. – NickLans Feb 18 '21 at 09:02
  • Do you get an error or something? And, yes, it is better to pass it as param. (https://expressjs.com/en/4x/api.html#req.params) – Naor Levi Feb 18 '21 at 10:21
  • no errors but I don't get the download. check unsplash.com how you can download an image to your local desktop on their images, I am trying to do exactly this. Wondering what I need to do with the file on the front end? I receive the file but how do I then download it? – NickLans Feb 18 '21 at 10:42
  • Hi Naor thanks for your help but I just solved it using anchor tags on the front end instead of making the fetch request. Still wondering if there is a way to use fetch to get to this result? – NickLans Feb 18 '21 at 11:38