Super simple file upload with node.js

Here’s a quick and dirty tutorial on how to upload files with node. I didn’t use any dependencies aside from “fs” that allows us to move the file from the temp location to where we need it to be. We’ll also use express to make it super easy.

First, add all required modules and create our server:

Now let’s render a page with a form:

And add a post method to handle uploads once the form is submitted.

First, check out log to see what you’re getting in res.files:

app.post('/', function(req, res){
console.log(JSON.stringify(req.files)); // this will let you see what you're getting in the files

});

And to complete this, we’ll actually need to save the uploaded file into our desired location, in my case it’s /public/images folder:

Note: in res.files object, make sure that your file name is the same name as the input field.
<input type="file" name="uploadfile" />
var temp_path = req.files.uploadfile.path;

Thanks to hacksparrow for the post on this.

Complete working example on github

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 )

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