Charith Amila Charith Amila - 28 days ago 6
Node.js Question

Node restful api, File upload and save file names in database before post

I have develop a node restful api. i need to upload some image files and save file names in to the database. how do it. this is my code

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;


This car_photos array is null. how i save this array my database. please help .

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

Answer

req.body.car_photos = car_photos; next();

these lines should be in the upload function call back. In the else block after the for loop.

Comments