Uploading the avatar photo to contacts
Let's start by creating the endpoint to upload avatar photos:
// routes.js
var controller = require('./controller');
//...
server.post('/api/contacts/:contactId/avatar',
controller.uploadAvatar);
Express itself does not process files automatically; it needs a plug-in that transforms the raw request into a more user-friendly API. This plug-in is named multer
; it processes multipart/form-data
, saving the file into a temporary path or making a buffer object, and then provides a JSON object with metadata information:
// Avatar endpoints var upload = multer(); server.post('/api/contacts/:contactId/avatar', upload.single('avatar'), controller.uploadAvatar ); server.use('/avatar', express.static(__dirname + '/avatar'));
With the default configuration, it will save all the uploaded files into the temporary path of your operating system, which is /tmp
in Unix systems; multer
will attach a files
attribute in the req
object, which we can inspect to retrieve information...