gpt4 book ai didi

json - NodeJS : saving renamed uploaded image to the database

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:44 26 4
gpt4 key购买 nike

我使用 jqgrid 插入数据。该数据还包括图像。上传没有问题,但我很难组合数据并重命名文件才能将其保存到数据库中。我尝试使用控制台检查它,似乎我的系统尝试调用插入模型两次。这是输出:

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(...);

这是我的代码,用于重命名上传的文件并将其保存到包含数据的数据库中。

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);

});
});
});
};

请容忍我糟糕的英语,非常感谢任何帮助。

最佳答案

执行异步操作时不要使用标准的 for 循环。使用 async 模块代替 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')
})
}

要安装上面示例所需的依赖项,请执行npm install -S eyespect async

关于json - NodeJS : saving renamed uploaded image to the database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16341435/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com