so I am using multer with gridfs to store my image on mongodb and when doing req.file the buffer field does not exist so therefore i do not know how to store the image or retrieve it properly
here is my current code
this is when creating a course and uploading an image
const createCourse = asyncHandler(async (req,res) => {
const {title, description, instructor, rating} = req.body;
const existingCourse = await Course.findOne({title});
const { filename } = req.file;
var buffer = req.file.buffer;
if (existingCourse) {
throw new ConflictError('Course title is already in usage.')
}
console.log(req.file)
console.log(filename)
console.log(buffer)
const course = await Course.create({
title,
description,
instructor,
rating,
image: filename,
sections: []
});
return res.status(201).json({_id: course.id, title: course.title})
});
my req.file looks like this:
{
fieldname: 'image',
originalname: 'strg.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
id: new ObjectId('659f2fd8c07837271b3faade'),
filename: '7d039fda-381b-4668-b4f1-db2fea4542d5.jpg',
metadata: null,
bucketName: 'uploads',
chunkSize: 261120,
size: 50593,
md5: undefined,
uploadDate: 2024-01-11T00:01:28.330Z,
contentType: 'image/jpeg'
}
and this is where i tried to retreive it:
const getCourseImage = async (req, res) => {
const courseId = req.params.courseId;
if (courseId.length !== 24) {
throw new InvalidInputError("Invalid course Id.");
}
const course = await Course.findById(courseId);
if (!course || !course.image) {
return res.status(404).send('Image not found');
}
console.log(course.image.data.buffer)
// const imageBuffer = Buffer.from(course.image.buffer, 'base64');
res.contentType('image/jpeg');
res.end(imageBuffer);
};
but I get an error saying the image has errors
this is my middleware for multer:
const multer = require('multer');
const {GridFsStorage} = require('multer-gridfs-storage');
const { v4: uuidv4 } = require('uuid');
const storage = new GridFsStorage({
url: 'mongodb://tes@localhost:27018/test',
file: (req, file) => {
const filename = `${uuidv4()}.${file.originalname.split('.').pop()}`;
return {
filename: filename,
bucketName: 'uploads',
};
},
});
const upload = multer({ storage });
module.exports = upload;
and I use it in router as this for uploading and then retreiving:
.post(courseValidationRules, upload.single('image'), (req, res, next) => {
createCourse(req, res,next);
})...
and this is how i retreive it in router:
router.get('/api/courses/:courseId/image', getCourseImage);
Been smashing my head on this, no idea how to fix it. thanks!