json - NodeJS: saving renamed uploaded image to the database -


im using jqgrid insert data. data includes images. uploading has no problem im having hard time combining data , renamed file in able save database. tried check using console , seems system try call insert model twice. output:

console.log (content.record);  { id: '_empty', logo: undefined, name: 'foo' } { id: 'undefined', logo: 'public/foo.jpeg',      name: 'undefined' } 

//it trying insert twice. maybe because of for(...);

this code rename uploaded file , save database data included..

exports.upload = function(req,res){            for(var in req.files)             var tmp_path = req.files[i].path;         for(var in req.files)          var target_path = newpath + req.files[i].name;                  fs.rename(tmp_path, target_path, function(err) {                   fs.unlink(tmp_path, function() {                      var content = {};                     content.table = "teams";                     content.record = {id:req.body.id,logo:target_path,name:req.body.name};                       //console.log(target_path);                 console.log(content.record);                          req.model.insert(content,function(err,result){                         result = (result?true:false);                          });                    });             }); }; 

please bear poor english, appreciated.

don't use standard for loop when performing asynchronous operations. use async module instead async.eachseries

var inspect = require('eyespect').inspector(); var fs = require('fs') var path = require('path') var async = require('async') exports.upload = function (req, res) {   var files = req.files   async.eachseries(     files,     function (file, cb) {       var filepath = file.path       var filename = file.filename       var outputpath = path.join(__dirname, 'uploads/', filename)       fs.rename(filepath, outputpath, function (err, reply) {         if (err) { return cb(err) }         var content = {};         content.table = "teams";         content.record = {           id:req.body.id,           logo:outputpath,           name:           req.body.name         };         //console.log(target_path);         console.log(content.record);         req.model.insert(content,function(err,result){           if (err) { return cb(err) }           inspect(result, 'insert result')           cb()         })       })     },     function (err) {       if (err) {         inspect(err, 'error saving files database')         res.send(500, err)         return       }       res.send(200, 'files saved correctly')     }) } 

to install needed dependencies example above execute npm install -s eyespect async


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

javascript - Clean way to programmatically use CSS transitions from JS? -

android - send complex objects as post php java -