In this tutorial, Let see how to Upload images to the database in MongoDB and Node js. Another Example to upload images in the database using MERN.
Library Required
- Body-parser
- Ejs
- Fs
- Mongoose
- Multer
- Nodemon
Folder ?Structure

Step1: Initialize
- Open command terminal and hit
D:\work\Codebun\Image-upload> npm init
- Require all library and dependencies
- Create a file name app.js
- Set up express to use server
const express = require("express"),
app = express(),
bodyParser = require("body-parser"),
fs = require("fs"),
multer = require("multer"),
mongoose = require("mongoose");
//Code to start server
app.listen(2000,function () {
console.log("Server Started at PORT 2000");
})
Step 2: Create Index
- Creating an index.ejs file in the views directory.
- Creating a form page to upload a photo.
- Using so that only image files can be uploaded.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Upload Image</h1>
<form action="/uploadphoto" enctype="multipart/form-data" method="POST">
<input type="file" name="myImage" accept="image/*">
<input type="submit" value="Upload Photo">
</form>
</body>
</html>
Step 3: Setting up the database and Multer
- Connecting to a Database
- Setting Schema
- Setting Multer
//Schema
var imgSchema = mongoose.Schema({
img:{data:Buffer,contentType: String}
});
var image = mongoose.model("image",imgSchema);
// SET STORAGE
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage })
Step 4: Setting routes
- Creating the index route (get route)
- Setting Up the /upload photos route (post route)
app.get("/",(req,res)=>{
res.render("index");
})
app.post("/uploadphoto",upload.single('myImage'),(req,res)=>{
var img = fs.readFileSync(req.file.path);
var encode_img = img.toString('base64');
var final_img = {
contentType:req.file.mimetype,
image:new Buffer(encode_img,'base64')
};
image.create(final_img,function(err,result){
if(err){
console.log(err);
}else{
console.log(result.img.Buffer);
console.log("Saved To database");
res.contentType(final_img.contentType);
res.send(final_img.image);
}
})
})
Use Command to start the server and run the website
D:\work\Codebun\Image-upload> node app.js
APP.js file
const express = require("express"),
app = express(),
bodyParser = require("body-parser"),
fs = require("fs"),
multer = require("multer"),
mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/Images");
app.use(bodyParser.urlencoded(
{ extended:true }
))
app.set("view engine","ejs");
//Schema
var imgSchema = mongoose.Schema({
img:{data:Buffer,contentType: String}
});
var image = mongoose.model("image",imgSchema);
// SET STORAGE
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage })
app.get("/",(req,res)=>{
res.render("index");
})
app.get("/show",(req,res)=>{
image.find().toArray(function (err,result){
const imgArray = result.map(element =>element._id);
console.log(imgArray);
if(err){
return console.error(err);
}
res.send(imgArray)
})
});
app.post("/uploadphoto",upload.single('myImage'),(req,res)=>{
var img = fs.readFileSync(req.file.path);
var encode_img = img.toString('base64');
var final_img = {
contentType:req.file.mimetype,
image:new Buffer(encode_img,'base64')
};
image.create(final_img,function(err,result){
if(err){
console.log(err);
}else{
console.log(result.img.Buffer);
console.log("Saved To database");
res.contentType(final_img.contentType);
res.send(final_img.image);
}
})
})
//Code to start server
app.listen(2000,function () {
console.log("Server Started at PORT 2000");
})