Simple File Upload with Express.js and Formidable in Node.js

Shiya Luo
Shiya Luo
Dec 19, 2015 · 1 min read

1. Setup

2. The Code

var express = require('express');
var formidable = require('formidable');

var app = express();

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

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');
});

app.listen(3000);
<!DOCTYPE html>
<html>
<head>
<title>Simple Upload Example</title>
</head>
<body>
<form action="/" enctype="multipart/form-data" method="post">
<input type="file" name="upload" multiple>
<input type="submit" value="Upload">
</form>
</body>
</html>

Shiya Luo

Written by

Shiya Luo

Posts on medium comes from my blog shiya.io.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade