Express provides feature to handle form data for uploading files and rendering their content, unfortunately most of the docs and tutorials I saw on internet were either outdated or didn’t work, so I making this post here to illustrate how to use and explain every point associated with it.

Step 1 : Enable bodyParser() in app.js

Express provides many middlewares to handle form data, to use this feature, first enable bodyParser middleware in your app.js file

app.use(express.bodyParser({uploadDir:__dirname+’/uploads’}));

bodyParser is just a wrapper around three other middlewares, one of these handles the multipart form data. Using the above code, all files will be uploaded in an  “uploads” directory of the current directory.
__dirname simply tells the current directory.

Step 2 : Create the File upload form in HTML or JADE

I’m writing the jade code for the simple form that has a file upload field with it

form(id=”uploadForm” method=”POST” action=”/” enctype=”multipart/form-data”,validate)

input(type=”file” name=”imageField” id=”imageField”)

Make sure you define enctype as mutipart/form-data to enable file uploads

Step 3: Handling Post Data

I’ve created a file handling service to deal with all file uploads, here is the substantial required code for the same,

All uploads files are available as request to the form handler, they can be find within req.files.{{uploadfield}} where {{uploadfield}} is the name of the input field where we are taking the file upload.
so, our code would something be like.

http://pastebin.com/h38x48qZ

Step 4 : Rendering Image content.

For this we will create another service which will map all image request and render the respective images
lets say, we want all images to be like image/1, image/2 … and so on image/{{imageid}} where {{imageid}} is the document id of the image.

create a route in your app.js file

app.get(“/image/:imageid”,function(req,res){

//:imageid will be save in req.paramas.imageid

var ImageAsset = require(‘../models/imageModel.js’);
var mongoose = require(‘mongoose’);
var path = require(‘path’);

var imageidn = req.params.imageid.toString();
var imageId = mongoose.Types.ObjectId(imageidn);

EventAsset.findOne({“_id”:imageId}, function(err,im imageasset){
if(err) console.log(“Unable to find a Thumbnail Asset associated with the given imageid” + err);

res.contentType(imageasset.mimeType);
res.sendfile(path.resolve(imageasset.filePath));
      });
});