Deep Vision Deep Vision - 4 months ago 184
Node.js Question

Any simple example of uploading image by NodeJs in FileSystem and saving the path in MongoDB?

I have been searching the net for a while, but I couldn't find any simple example of uploading multiple images in Filesystem using NodeJs+(maybe Multer) and saving their paths in MongoDB.

I have found this question the same, but it seems the answers are not working for me.
how to upload the image to folder using nodejs and save the path into mongodb?

So far I have been able to save the images in FileSystem.
here is what I have proceed so far.

package.json:

{
"name": "file_upload",
"version": "0.0.1",
"dependencies": {
"body-parser": "^1.14.2",
"express": "4.13.3",
"multer": "1.1.0"
},
"devDependencies": {
"should": "~7.1.0",
"mocha": "~2.3.3",
"supertest": "~1.1.0"
}
}


Server.js:

var express = require("express");
var bodyParser = require("body-parser");
var multer = require('multer');
var app = express();
app.use(bodyParser.json());
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage }).array('userPhoto',2);

app.get('/',function(req,res){
res.sendFile(__dirname + "/index.html");
});

app.post('/api/photo',function(req,res){
upload(req,res,function(err) {
//console.log(req.body);
//console.log(req.files);
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});

app.listen(3000,function(){
console.log("Working on port 3000");
});


Index.html:

<html>
<head>
<title>File upload Node.</title>
</head>
<body>
<form id="uploadForm"
enctype="multipart/form-data"
action="/api/photo"
method="post">
<input type="file" name="userPhoto" multiple />
<input type="submit" value="Upload Image" name="submit">
<input type='text' id='random' name='random'><br>
<span id = "status"></span>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
<script>
$(document).ready(function() {
$('#uploadForm').submit(function() {
$("#status").empty().text("File is uploading...");
$(this).ajaxSubmit({
error: function(xhr) {
status('Error: ' + xhr.status);
},
success: function(response) {
console.log(response)
$("#status").empty().text(response);
}
});
return false;
});
});
</script>
</body>
</html>


I really appreciate if you could give me some hint how I can add mongoDB here to save the path accordingly in mongoDB and how to retrieve the images in this case.

update answer: thanks to @flott

server.js

var express = require("express");
var bodyParser = require("body-parser");
var multer = require('multer');
var multerdragdrop = require('multer');
var app = express();
var http=require("http").Server(app);
var socket=require("socket.io")(http);
app.use(bodyParser.json());

//Path for loading static files
app.use("/FrontEnd/css",express.static(__dirname+'/public/FrontEnd/css'));
app.use("/FrontEnd/js",express.static(__dirname+'/public/FrontEnd/js')); app.use("/FrontEnd/partials",express.static(__dirname+'/public/FrontEnd/partials '));
app.use("/uploads",express.static(__dirname+'/uploads'));
app.use("/FrontEnd/Pictures",express.static(__dirname+'/public/FrontEnd/Pictures'));
var connect=require('./AdditionServerSide/MongoDbLib');

//Multer Storeage
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, __dirname+'/uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});

var upload = multer({ storage : storage }).array('userPhoto',8);
var uploaddragdrop=multerdragdrop({ storage : storage }).array('file',8);

app.get('/',function(req,res){
res.sendFile(__dirname + "/public/index.html");
});
//Image Upload form
app.post('/api/photo',function(req,res){
upload(req,res,function(err) {
//console.log(req.body);
console.log( req.files[0].destination);
//console.log( req.files[0].filename);
//console.log( req.files[0].path);

connect.addvalues('mongodb://localhost:27017/testimages','storedimages',req.file s[0].filename,req.files[0].destination);

if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");

});
});
//Drag and Drop Form Control
app.post('/photos',function(req,res){
uploaddragdrop(req,res,function(err){

if(err){

return res.end("Error Uploading file");
}else {
//console.log(req.files[0].originalname);

//connect.addvalues('mongodb://localhost:27017/testimages','storedimages',req.files[0].originalname,req.files[0].path);
return res.end("Success");
}

});

});
//******** Socket Function to receive data *********

socket.on('connection',function(socket){
socket.on('disconnect', function(){
// console.log("A user has disconnected");
});

socket.on('Latitude', function(msg){

// console.log("Latitude"+ msg);
});

socket.on('Longitude', function(msg){
// console.log("Longittude"+msg);
});

//Request from page to load images
socket.on("LoadImage",function(msg){
//Connect to data base and extract images
connect.establishConnection("mongodb://localhost:27017/testimages","storedimages ",null,null,function(results){
if(results!=undefined) {
if(msg.toUpperCase()=="YES"){
socket.emit("ImageUploads", results+','+__dirname);
}
}
})


});
});`


MongoDBLib.js

var mongodb = require('mongodb').MongoClient;

module.exports= {

establishConnection: function (connectionstring, databasename, queryby, queryval, callback) {
var filenames=[];
var filepaths=[];
var results;

mongodb.connect(connectionstring, function (err, db) {
if (callback) {
callback();
}
if (!err) {
var cursor=db.collection(databasename).find();
cursor.each(function(err,doc){
if(doc!=null) {
callback(doc.filename+","+doc.filepath);
}
})
}
else
console.log("Error happened");
});
},
addvalues: function (connectionstring, databasename, filename, filepath, callback) {
if (callback) {
callback();
}
mongodb.connect(connectionstring, function (err, db) {

var collec = db.collection(databasename);
if (collec != null) {
db.collection('storedimages').insert({
"filename": filename,
"filepath": filepath
}, {w: 1}, function (err, records) {

if (records != null) {
console.log("Record added");
db.close();
}
else
console.log("Cannot add");
});

}
else {
console.log("Database not found! error");
}
});
},

retrievevalues: function ( connectionstring, databasename, filename, filepath, callback) {
if (callback) {
callback();
}
mongodb.connect(connectionstring, function (err, db) {

var collec = db.collection(databasename);
if (collec != null) {
db.collection('storedimages').find({"filename":filename,"filepath":filepath},{w:1},function(err,records){
if(records!=null) {
console.log("Record retrieved");
db.close();
}
else
console.log("Cannot retrieve");
});

}
else {
console.log("Database not found! error");
}
});
}
}`

Answer

First of all, install mongoDB (if you haven't already) and make sure that it is running. Then you can connect to the mongoDB server by:

var mongo = require('mongodb');
var MongoClient = require('mongodb').MongoClient
var db;
MongoClient.connect('mongodb://localhost:27017/test', function(err, Db) {
    if (err) {
        console.log('Unable to connect to the mongoDB server. Error:', err);
    } else {
        console.log('CONNECTED TO MONGODB');
        db = Db;
    }
});

then you can insert things to the database in collection 'yourCollection' by:

var collection = db.collection('yourCollection');
collection.insertOne(data, (err, r) => {
    if (err) {
        console.log('Error:', err);
    } else {
        console.log('OK');
    }
});
Comments