node.jsmongodbmulter-gridfs-storage

Multer Grid Fs Storage downloading instead of displaying video in express


I am following a Tutorial From Travesy Media On MongoDB gridfs file uploads. So when I was trying to display the file in the web browser using readstream it downloads the video instead of displaying it! Here is my code for that function:

router.get('/get_one/:filename', (req, res) => {
  gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
    // Check if file
    if (!file || file.length === 0) {
      return res.status(404).json({
        err: 'No file exists'
      });
    }

    // Check if image
    if (file.contentType === 'image/jpg' || file.contentType === 'video/mkv' || file.contentType === 'video/mp4' || file.contentType === "video/wmv" || file.contentType === "video/avi" || file.contentType === "video/flw") {
      // Read output to browser
      const readstream = gfs.createReadStream(file.filename);
      readstream.pipe(res);
    } else {
      res.status(404).json({
        err: 'Not an image'
      });
    }

Please Help Me! I Don't Know How To Fix This! PS: The file.contentType === "image/jpg" is something that I tried


Solution

  •     const readstream = gfs.createReadStream(file.filename);
          res.set('Content-Type',file.contentType)
          readstream.pipe(res);