I have a struggle with displaying an images, retrieved from mongoDB, where it is saved as a binary data. I'm using Multer for storing images to database. Images are stored into database correctly, but when I try to display them and covert them to base64, I've got this error: Cannot read property 'toString' of undefined...
Here is my code:
var storage = multer.diskStorage({
destination: './public/uploads/',
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now())
}
});
var upload = multer({storage: storage});
router.post('/', upload.single('image'), async (req, res, next) => {
console.log(res);
req.book = new Book();
next();
}, postOrEditBook('new'));
function postOrEditBook(page) {
return async (req, res) => {
let book = req.book;
book.img = {
data: fs.readFileSync(path.join( './public/uploads/' + req.file.filename)),
contentType: 'image/png'
}
try {
book = await book.save();
if(page == 'new') {
res.redirect('/list');
} else {
res.redirect(`/books/${book.slug}`);
}
} catch (e) {
res.render(`articles/${page}`, { book: book })
}
}
}
In schema images are stored like this:
const bookSchema = new mongoose.Schema({
img: {
data: Buffer,
contentType: String
}
});
Input field for the file:
<form action="/books" method="POST" autocomplete="off" enctype="multipart/form-data">
<input type="file" name="image"">
</form>
Image into mongodb looks like this: img: Object :Binary('iVBORw0KGgoAAAANSUhEUgAABVYAAAMACAIAAABAXKuVAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMA...', 0) contentType: "image/png"
And, I've tried to display images in ejs file like this:
<div>
<% books.forEach(book => { %>
<img src="data:book/<%= book.img.contentType %>;base64,
<%= book.img.data.toString('base64') %>">
<% }) %>
</div>
Can anyone tell me what I'm doing wrong? I really can't figure out what the problem is. I can't find anything that would help me solve this problem...