There is a great library to handle file uploads for Node.js Express framework. It is a Multer module.
Let's install it:
$npm install multer --save
The configuration of Multer is pretty straightforward. We will use it as a middleware after our authentication to be sure that only the authenticated request uploads files to the service. We will use the following code for this purpose:
var multer = require('multer'); router.post('/', jwtauth, requireAuth, multer({ dest: './public/uploads/', rename: function(fieldname, filename) { return Date.now(); } }), function(req, res, next) { var picture = req.body; if (req.files && req.files && req.files.picture) { picture.fileName = req.files.picture.name; } // save to the DB code goes here });
Where:
dest
is the destination directory for the uploaded files.rename
is a customized function to assign new...