Skip to content

Instantly share code, notes, and snippets.

@edin-m
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edin-m/47e45184622b37c21823 to your computer and use it in GitHub Desktop.
Save edin-m/47e45184622b37c21823 to your computer and use it in GitHub Desktop.
formidable form file upload
var express = require('express');
var formidable = require('formidable');
var app = express.createServer();
var AppController = {};
// AppController is synonym for another file's module.exports
AppController.uploadFile = function(req, res, next) {
var form = new formidable.IncomingForm();
form.uploadDir = '/tmp';
form.on('file', function(field, file) {
var dst = path.join('uploads', req.user._id.toString());
// here you can save to req.body some file specifics
// such as dst file path and etc...
// to be able to plug it into nex middleware and reuse
// you can refactor this function to a constructor that returns a function
// with specific upload basedir
// or rather yet upload basedir callback
fs.createReadStream(file.path)
.pipe(fs.createWriteStream(dst))
.on('error', next.bind(null))
.on('finish', function() {
// ... same as above
// remove original file
fs.unlink(file.path);
next();
});
});
form.on('field', function(field) {
console.log([].slice.call(arguments));
});
form.on('error', next.bind(null);
form.parse(req);
};
app.route('/upload')
.post(AppController.uploadFile);
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment