首页 > 解决方案 > Multer Grid Fs 存储下载而不是快速显示视频

问题描述

我正在关注 Travesy Media 关于 MongoDB gridfs 文件上传的教程。因此,当我尝试使用 readstream 在网络浏览器中显示文件时,它会下载视频而不是显示它!这是我的该功能的代码:

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"是我尝试过的东西

标签: node.jsmongodbmulter-gridfs-storage

解决方案


  • 记录 file.contentType 并找出是否获得“filetype/fileExtension”,例如 image/jpeg、video/mp4 以及是否没有。只需在文件扩展名上使用正则表达式设置它

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

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

推荐阅读