Book Image

PhoneGap By Example

Book Image

PhoneGap By Example

Overview of this book

Table of Contents (17 chapters)
PhoneGap By Example
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Implementing file upload on the service side


There is a great library to handle file uploads for Node.js Express framework. It is a Multer module.

Tip

Multer is a middleware that handles multipart/form-data.

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...