node.js - 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"
是我尝试过的东西
解决方案
记录 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);
推荐阅读
- javascript - 在移动设备中查看时如何仅显示一定数量的页面?
- google-apps-script - 将查找特定值并在满足条件时将其替换为另一个工作表中的公式的 Google Apps 脚本
- python - 在 python 中处理大型列表的最有效方法
- swift - SwiftUI:如何让手机振动?
- c++ - 未初始化的 C++ 指针的默认行为是什么
- java - 调用构造函数时抛出异常,java.lang.NullPointerException
- python-3.x - 如何在 python 中具有多个线程的线程程序中添加延迟?
- ansible - ansible成为&-K如何与ssh用户名和ssh密码相关
- ios - 在组合中将发布者的错误类型转换为从不
- double - 蜂巢猪双精度