It is quite long time, I have no new post. Today, I will show you the way to upload files by using NodeJS. In my way, I used connect-busboy packet and ExpressJS 4.0.

In the new world, it is not the big fish, which eats the small fish, it’s the fast fish which eats the slow fish
At the first, create the directory tree as below:
1 2 3 4 5 6 7 8 |
$ tree . . ├── apis │ ├── index.js │ └── upload.js ├── app.js ├── packages.json └── uploads |
See app.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
'use strict'; var express = require('express'); var app = express(); // images app.use('/upload', express.static(__dirname + '/uploads')); app.use(require('./apis')); // Start web server at port 3000 var port = 3000; var server = app.listen(port, function () { var host = server.address().address; var port = server.address().port; console.log('Server start at http://%s:%s', host, port); }); |
See index.js file:
1 2 3 4 5 6 7 8 9 10 11 12 |
'use strict'; var express = require('express'), router = express.Router(); router.use('/api/v1/upload', require('./upload')); // nothing for root router.get('/', function(req, res){ res.send(JSON.stringify({})); }); module.exports = router; |
See upload.js file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
'use strict'; var express = require('express'), router = express.Router(), fs = require('fs'), path = require('path'), busboy = require('connect-busboy'); router.use(busboy()); router.post('/', function(req, res) { var fstream; req.pipe(req.busboy); req.busboy.on('file', function (fieldname, file, filename) { var filePath = path.join(__dirname, '/../upload/', filename); fstream = fs.createWriteStream(filePath); file.pipe(fstream); fstream.on('close', function () { console.log('Files saved'); })); }); }); }); module.exports = router; |
Now, you can run upload file application:
1 |
node app.js |
And if you want to view the uploaded images, you should use the source code below in app.js:
1 2 3 4 5 |
app.get('/image/:fileName', function(req ,res) { var path = require('path'); var file = path.join(__dirname, 'uploads/', req.params.fileName); res.sendFile(file); }); |