Last active
August 29, 2015 14:16
-
-
Save edin-m/47e45184622b37c21823 to your computer and use it in GitHub Desktop.
formidable form file upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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