Multer Grid Fs Storage 下载而不是在 express 中显示视频

问题描述

我正在学习来自 Travesy Media On MongoDB gridfs 文件上传的教程。因此,当我尝试使用 readstream 在 Web 浏览器中显示文件时,它会下载视频而不是显示它! 这是我的函数代码

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'
      });
    }

请帮帮我!我不知道如何解决这个问题! PS:file.contentType === "image/jpg" 是我尝试过的

解决方法

  • 记录 file.contentType 并找出是否得到“filetype/fileExtension”,例如图像/jpeg、视频/mp4,如果没有得到。只需使用文件扩展名上的正则表达式设置它

  • 在将流传输到响应之前尝试在响应中设置 Content-type 标头;

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