Im using jqgrid to insert data. This data also includes images. Uploading has no problem but Im having a hard time combining data and renamed file in able to save it into the database. I tried to check it using console and it seems like my system try to call insert model twice. This is the output:
console.log (content.record);
{
id: '_empty',
Logo: undefined,
Name: 'foo'
}
{
id: 'undefined',
Logo: 'public/foo.jpeg',
Name: 'undefined'
}
//it always trying to insert twice. Maybe because of the for(...);
This is my code to rename the uploaded file and save it into the database with data included..
exports.Upload = function(req,res){
for(var i in req.files)
var tmp_path = req.files[i].path;
for(var i 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 WITH MY POOR ENGLISH, ANY HELP WILL BE MUCH APPRECIATED.
Don't use a standard for loop when performing asynchronous operations. Use the async module instead with the 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 to database')
res.send(500, err)
return
}
res.send(200, 'files saved correctly')
})
}
To install the needed dependencies for the example above execute
npm install -S eyespect async