Node.js – a quick start file upload guide, Part 2

Welcome back! So, yesterday we looked at how we can use the Node.js Express package to spin up a server and deliver one or more flat html pages to the browser. We’re going to take that further now and put in a form to let us upload a file.

If you didn’t catch yesterday’s post, you can read it here. You should do that now and then come back. As mentioned, this is all based heavily off the guidance give at http://shiya.io/simple-file-upload-with-express-js-and-formidable-in-node-js/, so credit where credit’s due.

Okay, let’s go!

Step 6: Build the form

This is probably the easiest bit. Here’s the form. Drop it into your index.html after the P tag:

NOTE: As with last time, I’ve dropped the HTML into a Google Doc which you can find here: https://docs.google.com/document/d/1mNO8zIxTsoy84VlGcDWYMhgxOZ5YTy8YGCd8y-uetgE/edit?usp=sharing

That’s all you need to do. The form will take a file via the upload field and send it in POST to the web root at /. Now we need to get our app to intercept that POST and do something with it.

Step 7: Install Formidable

To process the form data we need the Node package, Formidable. You can find out a bit more about that here: https://github.com/felixge/node-formidable. So, head to your terminal, make sure you’re in your project folder and fire up:

npm install --save formidable

Done. Let’s get back to our app.

Step 8: Handle the POST

Head back into app.js. We need to add a few things here to be able to deal with that form data that’s coming through. First off, let’s load in Formidable with:

var formidable = require(‘formidable’);

No we need to tell Express how to handle a POST on the web root. We need a new route to do that, and in that route we’ll call Formidable and get it to process the form we’ve received. Here’s what it looks like:

app.post('/', function(req, res){
   var form = new formidable.IncomingForm();

   form.parse(req);

   form.on('fileBegin', function(name, file){
       file.path = __dirname + '/uploads/' + file.name;
   });

   form.on('file', function (name, file){
       console.log('Uploaded ' + file.name);
   });

   res.sendFile(__dirname + '/index.html');
});

So what’s happening here is a couple of things. On a POST call to the web root, Express instantiates an IncomingForm on our Formidable object. It then looks for any file elements within passed form data (in the request object) and uploads them to a folder called uploads. It then logs to the console that it’s done this before showing the user the index.html page.

One thing we’ve got missing now is that uploads folder, so go ahead and create it in your web root.

Spin up your server, try out the form and you should find that the file you throw at it will go into your uploads folder. Congratulations! You’ve created a working Node.js app! For reference, the full app.js is:

var express = require('express');
var formidable = require('formidable');
var app = express();
var port = 3000;

//Routes - GET
app.get('/', function (req, res){
   res.sendFile(__dirname + '/index.html');
});

app.get('/about', function (req, res){
   res.sendFile(__dirname + '/about.html');
});

//Routes - POST
app.post('/', function(req, res){
   var form = new formidable.IncomingForm();

   form.parse(req);

   form.on('fileBegin', function(name, file){
       file.path = __dirname + '/uploads/' + file.name;
   });

   form.on('file', function (name, file){
       console.log('Uploaded ' + file.name);
   });

   res.sendFile(__dirname + '/index.html');
});

//Listen
app.listen(port, () => console.log(`App listening on port ${port}`))

Further reading

Where to now? I mentioned a few things the other day but, since writing part 1, I’ve been reading further on how Node.js handles forms and it seems that the Formidable method, while functional, has been superceded by some other packages. I’ll be taking a look at these in the future. Also, it’s great running this app on your local machine, but getting it up on a server and doing something with the uploaded goal of this piece. Next step for me is actually doing that and looking into how to effectively run Node apps long term.

Thanks for now! As always, if you’ve got any thoughts or comments, do chime in!

Advertisements

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s