DEV Community

Discussion on: Uploading Files to MongoDB with GridFS and Multer Using NodeJS

Collapse
 
zubairdroid profile image
Syed Zubair(zubi-droid)

Thank you for this post sir.. Now I can upload my files to my mongo-atlas cluster successfully. Its very kind of you on my reach to this. I can now see the uploaded collections binary data on the collections (upl.files , upl.chunks) in mongo-atlas.

But I can't find a way to download a pdf file that i uploaded sir...Can u please help me on how to download a uploaded pdf file to my database sir. :{ Help sir.

Collapse
 
shubhambattoo profile image
Shubham Battoo

Hi Syed, you can do something like this to download a pdf or any other file for this matter

<a href="image/<%= file.filename %>" download><%= file.filename %></a>

I have created a route "image/:filename" which then downloads the image which is not limited to a image and can handle any other file types also, but for this demo I was only downloading images.

app.get("/image/:filename", (req, res) => {
  // console.log('id', req.params.id)
  const file = gfs
    .find({
      filename: req.params.filename
    })
    .toArray((err, files) => {
      if (!files || files.length === 0) {
        return res.status(404).json({
          err: "no files exist"
        });
      }
      gfs.openDownloadStreamByName(req.params.filename).pipe(res);
    });
});
Collapse
 
zubairdroid profile image
Syed Zubair(zubi-droid) • Edited

Thank you so much for your help sir. What I have to do if i need to download the file that the user uploads from his end, and I have to download that from the database collection but not from the user side itself. if i'm not wrong, Like in google classroom app., we upload our assignments as .pdf to our professor and those attachments reaches him/her in their database(provided by that app.) and they download them on their end..... Is there any way to implement like this, sir. Any help would be appreciated.

Collapse
 
vasantisuthar profile image
Vasanti Suthar • Edited

Hey, thanks for this blog. I have implemented this but the file is not being able to download it says couldn't download.