Created
May 30, 2014 08:42
-
-
Save simonexmachina/cddf06e26abdd678bd03 to your computer and use it in GitHub Desktop.
File uploads in Node.js
This file contains hidden or 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 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