Reputation: 103
I was trying to upload images to mongodb database. And Then got this error which I am not able to resolve. Can someone help!
The code after all the require statements is show below
// MONGOOSE CONNECTION
const conn = mongoose.createConnection(mongoURI);
// GRID FS
let gfs;
conn.once('open' , ()=>{
// init stream
gfs = Grid(conn.db , mongoose.mongo);
gfs.collection('uploads');
});
// MULTER
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'uploads'
};
resolve(fileInfo);
});
});
}
});
const upload = multer({storage}).single('file');
Then When i tried to show the file object saved in the database using gfs.file.find(), it worked
app.get("/files/:filename" , (req , res)=>{
gfs.files.findOne({filename : req.params.filename} , (err , file)=>{
if(!file){
return res.json({err : "No file exists"});
}
return res.json(file)
})
});
The above code worked and showed the json object when called. But when tried to show the image not as json but as the actual image using createReadStream , It broke
app.get("/image/:filename" , (req , res)=>{
gfs.files.findOne({filename : req.params.filename} , (err , file)=>{
if(!file){
return res.json({err : "No file exists"});
}
// file exists
// if it is an image
if(file.contentType === 'image/jpeg' || file.contentType === 'image/png'){
// Read output to browser
const readstream = gfs.createReadStream(file.filename);
readstream.pipe(res);
}
else{
res.status(404).json({err : "not an image"});
}
});
});
Upvotes: 2
Views: 341