Skip to content

Instantly share code, notes, and snippets.

@simonexmachina
Created May 30, 2014 08:42
Show Gist options
  • Select an option

  • Save simonexmachina/cddf06e26abdd678bd03 to your computer and use it in GitHub Desktop.

Select an option

Save simonexmachina/cddf06e26abdd678bd03 to your computer and use it in GitHub Desktop.
File uploads in Node.js
var multiparty = require('multiparty'),
mkdirp = require('mkdirp'),
path = require('path'),
fs = require('fs');
module.exports = function handleFileUpload(req, res, saveDir, cb) {
var form = new multiparty.Form();
mkdirp(saveDir, function(err) {
if (err) return cb(err);
form.parse(req, function(err, fields, files) {
if (err) return cb(err);
try {
for (var key in files) {
files[key].forEach(moveFile);
}
}
catch(err) {
return cb(err);
}
cb(null, fields, files);
function(file, index) {
var savePath = path.resolve(saveDir, file.originalFilename);
fs.renameSync(file.path, savePath);
files[key][index].path = savePath;
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment