Monday, February 06, 2012

Node.js express file upload -- uploading file the easy way

Forget all those old example on how to upload file. Express provides a very easy and simple to use file upload feature that every newbie (like me) should know and use.

Step 1:
Your form must be multipart.

<form  enctype="multipart/form-data"
...>
<input name="uploadfile" type="file />

Step 2:
Here comes the req.files magic.

app.post('/upload', function(req, res) {
     console.log( req.files.uploadfile );
     console.log( req.files.uploadfile.name );

     // use fs.rename to move the file and unlink after that
});

Internally express is using formidable to do handle the file upload. But it's a surprise to me that formidable doc is a piece of shit, and express is obviously not advertising this feature enough.

1 comment:

godu said...

Thx dude, i was just looking for this way to upload files (without use formidable-like).