Skip to content

Commit

Permalink
Auto-calculate file size when grokking uploaded files. Multer does no…
Browse files Browse the repository at this point in the history
…t do this itself (but should).
  • Loading branch information
Steve Krenek committed Apr 8, 2014
1 parent 1604a47 commit 8ebc1cd
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions lib/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,36 @@ exports.getMiddleware = function(options, cb) {
}
var bodyParserMiddleware = bodyParser();
var multerOptions = _.extend({}, appOptions.safeGet('connect.bodyParser.multipart'), appOptions.fileUploadOptions);

// Multer does not calculate file size. Do it on our own.
if (multerOptions.onFileUploadStart) {
var _fileUploadStart = multerOptions.onFileUploadStart;
multerOptions.onFileUploadStart = function(file) {
file.contentLength = 0;
file.size = 0; // backwards compatibility
_fileUploadStart.call(multerOptions, file);
};
} else {
multerOptions.onFileUploadStart = function(file) {
file.contentLength = 0;
file.size = 0; // backwards compatibility
};
}

if (multerOptions.onFileUploadData) {
var _fileUploadData = multerOptions.onFileUploadData;
multerOptions.onFileUploadData = function(file, data) {
file.contentLength += data.length;
file.size = file.contentLength; // backwards compatibility
_fileUploadData.call(multerOptions, file, data);
}
} else {
multerOptions.onFileUploadData = function(file, data) {
file.contentLength += data.length;
file.size = file.contentLength; // backwards compatibility
}
}

var multerMiddleware = multer(multerOptions);

var restRouter = RESTful(options, files.restFiles || []);
Expand Down Expand Up @@ -128,6 +158,8 @@ exports.getMiddleware = function(options, cb) {
if (err) return next(err);
if (! req._body) {
multerMiddleware(req, res, function() {
// While multer will populate req.body, since multi-part requests upload everything as
// text data types are lost (all are strings). This allows a shim to keep your data types if necessary.
if (req.body.body) {
try {
req.body = JSON.parse(req.body.body);
Expand Down

0 comments on commit 8ebc1cd

Please sign in to comment.