I have a back end using node.js and a front end using jquery, javascript, ajax and bootstrap. I want to upload an image from front end and save it to the mongoose database. Here the file is loading successfully and image will be in the location called /public/img. But how can I save those image information into the database using an API call.
Below is my code:
Backend Code Node.js, Mongoose
/server.js
var express = require("express"); var multer = require('multer'); var path = require('path'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var app = express(); app.appname="photogallery"; //config mongoose app.db = mongoose.createConnection('localhost/'+app.appname); app.db.on('error', console.error.bind(console, 'mongoose connection error: ')); app.db.once('open', function () { //Storage is all good }); //Routes and acl var router = express.Router(); require('./routes')(app, router, passport); var file_url = ''; var storage = multer.diskStorage({ destination: function (req, file, callback) { callback(null, 'public/img/'); }, filename: function (req, file, callback) { callback(null, file.fieldname + '-' + Date.now()); file_url = file.fieldname + '-' + Date.now() + '.' + file.originalname.split('.')[file.originalname.split('.').length -1] callback(null, file_url); } }); var upload = multer({ storage : storage}).single('userPhoto'); app.use(express.static(path.join(__dirname, '/public/'))); app.post('/api/photo',function(req,res){ upload(req,res,function(err) { if(err) { return res.end("Error uploading file."); } // res.end("File is uploaded"); res.json({error_code:0,err_desc:null,file_url:'img/'+file_url}); /*Now I want to save this file_url to image_url using api /api/photoGallery, please help me to save these information to the db */ }); }); //config express app.set('secret','thisshouldnotbeinplaintext'); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(passport.initialize()); app.use(router); app.listen(5050,function(){ console.log("Working on port 5050"); }); /api/requests.js
'use strict'; var passport = require('passport'); var app = require('../app'); exports.init = function(pp) { passport = pp; app = pp; return exports; }; exports.root = function(req, res) { res.send("Running"); }; //Add Image Data exports.addData = function(req, res) { var addData = req.app.db.model('Data'); var data = { image_title : req.body.image_title, image_url : "http://localhost:5050/"+req.body.image_url } var query = addData(data); query.save(function(err){ if(err){ console.log(err.toString()); } console.log('Image Saved Successfully'); res.json({ success: true }); }); }; /schema/Data.js
'use strict'; exports = module.exports = function(app, mongoose) { var dataSchema = new mongoose.Schema({ image_title : { type: String, unique: true, lowercase: true }, image_url : { type: String, unique: true, lowercase: true } }); app.db.model('Data', dataSchema); }; /models.js
'use strict'; module.exports = function(app, mongoose) { //Mongoose Schemas require('./schema/Data')(app, mongoose); }; /routes.js
'use strict'; module.exports = function(app, router, passport) { var requests = require('./api/requests').init(passport); router.get('/', requests.root); router.post('/api/addPhoto/v1', requests.addData); router.get('/api/getPhoto/v1', requests.getPhoto); }; e.g Json Will Be like below
{ image_title: exampleImage, image_url: xyzscjnscncsl.exampleImage.png } Frontend Code Jquery, JavaScript, Ajax, HTML
/public/index.html
<div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">Please Upload Image</h4> </div> <form id="uploadForm" enctype="multipart/form-data" action="/api/photo" method="post"> <div class="modal-body"> <div class="form-group"> <input type="text" class="form-control" id="imagetitle" placeholder="Image Title"> </div> <div class="form-group"> <input type="file" class="form-control" id="input-image" name="userPhoto" accept="image/*"> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancle</button> <button type="submit" class="btn btn-default" value="Upload Image" name="submit">Save</button> </div> <span id = "status"></span> </form> </div> </div> </div> /public/javascript/image.js
How to save image data from here to the mongoose db using an API call?
$(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; }); });