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
log the file.contentType and find out if you get "filetype/fileExtension" eg image/jpeg, video/mp4 and if you don't get such. just set it using a regular expression on file Extension
Try setting the Content-type header in the response before piping stream to response;
const readstream = gfs.createReadStream(file.filename);
res.set('Content-Type',file.contentType)
readstream.pipe(res);