Currently, in my project, I am saving image files to MongoDB using multer. I am doing this by converting the image into base64 format and then saving that data. This works, but it takes up a lot of storage in the database, slowing down my application. I was wondering if there was a way to convert the file into a URL and then save that URL into the database.
This would turn something like this: iVBORw0KGgoAAAANSUhEUgAAAyAAAAMgCAIAAABU...
Into something like this: something.com/imageurl.
Here is my current code:
var multer = require("multer");
var upload = multer({
storage: multer.memoryStorage(),
limits: {fileSize: 1 * 2048 * 2048},
fileFilter: function fileFilter(req, file, cb){
if(file.mimetype !== 'image/png' | "image/jpg" | "image/jpeg"){
return cb(new Error('Something went wrong'), false);
}
cb(null, true);
}
}).fields([{ name: 'fileone', maxCount: 1 }, { name: 'filetwo', maxCount: 1 }]);
module.exports = upload;
app.post("/create", function(req, res){
upload(req, res, function(err){
if(err){
res.render("create", {msg: "Error: Please Keep each file under 1mb and only upload PNG, JPG, or JPEG images"});
} else{
var fileOne = req.files["fileone"][0].buffer.toString("base64");
var fileTwo = req.files["filetwo"][0].buffer.toString("base64");
var title = req.body.title;
var newPosts = {title: title, fileOne: fileOne, fileTwo: fileTwo}
Post.create(newPosts, function(err, newlyCreated){
if (err){
console.log(err);
} else{
res.redirect("/posts/" + newlyCreated._id);
}
});
}
});
})