I just finished a solution for this. This solution works with Ajax, so you can use fetch
calls in Javascript with this. The strange thing is that nowhere on the whole internet this solution could be found and thats why I put in on to help others who want to work with images with data uris :-)
Model:
cmsImage: { data: Buffer, contentType: String }
Storing in MongoDB:
let rawData = fs.readFileSync(`${root}public/uploads/` + file.originalname);
let base64Data = Buffer.from(rawData).toString('base64');
// upload this image
let image = {
cmsImage: {
data: base64Data,
contentType: file.mimetype
}
};
// in this record in the database
await this.model.findByIdAndUpdate(body.id, image);
Retrieving from MongoDB and create image element dynamically:
// decode image from database as image uri
let imageArray = new Int8Array(image.data.data);
let decodedImage = new TextDecoder().decode(imageArray);
// image
let cmsImage = document.createElement("img");
cmsImage.src = "data:" + image.contentType + ";base64," + decodedImage;
cmsImage.alt = "image";
cmsContent.appendChild(cmsImage);
Multer - Use originalfile for upload to database.
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/uploads')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
});
this.upload = multer({ storage: storage });
upload to directory
this.upload.single(uploadImage)