我开发了一个节点restful api。我需要上传一些图像文件并将文件名保存到数据库中。怎么做这是我的代码
var express = require('express');
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var router = express.Router();
var path = require('path');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback)
{
callback(null, Date.now('nano') + path.extname(file.originalname));
}
});
var upload = multer({ storage : storage }).array('userPhoto',2);
// Models
var Car = require('../models/car');
// Routes
Car.methods(['get','put','post','delete']);
// before file uplod part
Car.before('post',function(req,res,next)
{
var car_photos = [];
upload(req,res,function(err)
{
if(err)
{
return res.end("Error uploading file.");
}
else
{
for(var i = 0; i < req.files.length; i++)
{
car_photos.push(req.files[i]['filename']);
}
}
});
req.body.car_photos = car_photos;
next();
});
Car.register(router,'/car');
module.exports = router;
此car_photos数组为空。我如何保存这个数组我的数据库。请帮忙。
Car.before('post',function(req,res,next)
{
var car_photos = [];
upload(req,res,function(err)
{
if(err)
{
return res.end("Error uploading file.");
}
else
{
for(var i = 0; i < req.files.length; i++)
{
car_photos.push(req.files[i]['filename']);
}
}
});
req.body.car_photos = car_photos;
next();
});
答案 0 :(得分:1)
req.body.car_photos = car_photos; 下一个();
这些行应该在上传函数回调中。在for循环之后的else块中。
答案 1 :(得分:0)
此示例适用于使用库节点 - restful
的任何人
https://github.com/baugarten/node-restful
为模型添加一个字段:
car_photos: Array
var express = require('express');
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var router = express.Router();
var path = require('path');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback)
{
callback(null, Date.now() + path.extname(file.originalname));
}
});
var upload = multer({ storage : storage }).array('car_photos',2);
// Models
var Car = require('../models/car');
// Routes
Car.methods(['get','put','post','delete']);
// before file uplod part
Car.before('post',function(req,res,next)
{
var car_photos = [];
upload(req,res,function(err)
{
if(err)
{
return res.end("Error uploading file.");
}
else
{
for(var i = 0; i < req.files.length; i++)
{
car_photos.push(req.files[i]['filename']);
}
req.body.car_photos = car_photos;
next();
}
});
});
Car.register(router,'/car');
module.exports = router;