Prash's Blog

Upload and Display File in NodeJS Application April 18, 2012

Filed under: Nodejs — prazjain @ 2:46 pm
Tags:

In this post we will build up on the simple nodejs application we wrote earlier and add the functionality to allow user to upload a pdf file and show the pdf back to the user.
I will not be describe the old code as we have already read a lot of documentation on it in previous post.
So lets start coding and there will be comments for new code in between :

Index.js :

var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandler");
var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
handle["/show"] = requestHandlers.show;
server.start(router.route,handle);

Server.js

var http = require("http");
var url = require("url");
function start(route,handle)
{
 function onRequest(request, response)
 {
 var pathname = url.parse(request.url).pathname;
 console.log("Request for " + pathname + " received.");
 route(handle,pathname, response, request);
 }
 http.createServer(onRequest).listen(9999);
 console.log("Server has started.");
}
exports.start = start;

Router.js

function route(handle,pathname,response,request)
{
 console.log("About to route a request for " + pathname);
 if (typeof handle[pathname]==='function')
 {
 handle[pathname](response,request);
 }
 else
 {
 console.log("No request handler found for " + pathname);
 response.writeHead(404,{"Content-Type":"text/plain"});
 response.write("404 Not found");
 response.end();
 }
}
exports.route = route;

Finally requestHandler.js, this is the file where we make change to allow uploading a file, and then displaying it back in the browser.
Before this, you will need to install a package called formidable, this package makes it easy to upload and deal with all the file processing relating to upload. Install it using this command :

npm install formidable

requestHandler.js contents :

var querystring = require("querystring");
var formidable = require("formidable");
var fs = require ("fs");

function start(response)
{
 console.log("Request handler start was called.");
 var body = "<html>" +
 "<head>" +
 "<meta http-equiv='Content-Type' content='text/html'; " +
 "charset='UTF-8' />" +
 "</head>" +
 "<body>" +
 "<form action='/upload' enctype='multipart/form-data' method='post'>" +
 "<input type='file' name='upload'></input>" +
 "<input type='submit' value='Upload file' />" +
 "</form>" +
 "</body>" +
 "</html>" ;
 response.writeHead(200,{"Content-Type":"text/html"});
 response.write(body);
 response.end();
}
function upload(response,request)
{
 console.log("Request handler upload was called.");
 var form = new formidable.IncomingForm();
 console.log("about to parse");
 form.parse(request, function(error,fields,files)
 {
 console.log("parsing done");
 /* possible error on windows systems :
 tried to rename to an already existing file */
 fs.rename(files.upload.path,"c:\\tmp\\test.pdf", function (err)
 {
 if (err)
 {
 fs.unlink("c:\\tmp\\test.pdf");
 console.log("Value of files.upload.path : " + files.upload.path );
 fs.rename(files.upload.path,"c:\\tmp\\test.pdf");
 }
 });
 response.writeHead(200, {"Content-Type" : "text/html" } );
 response.write("Received pdf: <br/>");
 response.write("<a href="/show">/show</a>");
 response.end();
 });
}

function show(response, request)
{
 console.log("Request handler show was called.");
 fs.readFile("c:\\tmp\\test.pdf","binary", function(error,file)
 {
 if (error)
 {
 response.writeHead(500, {"Content-Type": "text/plain" });
 response.write(error + "\n");
 response.end();
 }
 else
 {
 response.writeHead(200, {"Content-Type" : "application/pdf" });
 response.write(file, "binary" );
 response.end();
 }
 });
}
exports.start = start;
exports.upload = upload;
exports.show = show;

And then run the app :

node index.js

You will be able to upload the file and see the pdf back as embedded in page in the browser.

Advertisements
 

One Response to “Upload and Display File in NodeJS Application”

  1. Yss Nibode Says:

    it does not work with me


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s