c85c0558b9
one idea is just use express.raw() . however, we have to implement some file size limit there. one case this does not handle is aborted uploads from a box.service restart. for this rare case, a server reboot will clean up /tmp anyway.
52 lines
1.7 KiB
JavaScript
52 lines
1.7 KiB
JavaScript
/* jshint node:true */
|
|
|
|
'use strict';
|
|
|
|
const multiparty = require('multiparty'),
|
|
safe = require('safetydance'),
|
|
timeout = require('connect-timeout');
|
|
|
|
function _mime(req) {
|
|
const str = req.headers['content-type'] || '';
|
|
return str.split(';')[0];
|
|
}
|
|
|
|
module.exports = function multipart(options) {
|
|
return function (req, res, next) {
|
|
if (_mime(req) !== 'multipart/form-data') return res.status(400).send('Invalid content-type. Expecting multipart');
|
|
|
|
const form = new multiparty.Form({
|
|
uploadDir: '/tmp',
|
|
keepExtensions: true,
|
|
maxFieldsSize: options.maxFieldsSize || (2 * 1024), // only field size, not files
|
|
limit: options.limit || '8mb', // file sizes
|
|
autoFiles: true // emit files instead of emitting 'part'
|
|
});
|
|
|
|
// increase timeout of file uploads by default to 3 mins
|
|
if (req.clearTimeout) req.clearTimeout(); // clear any previous installed timeout middleware
|
|
|
|
timeout(options.timeout || (3 * 60 * 1000))(req, res, function () {
|
|
req.fields = {};
|
|
req.files = {};
|
|
|
|
form.parse(req, function (error, fields, files) {
|
|
if (error) {
|
|
for (const file in files) safe.fs.unlinkSync(file.path);
|
|
return res.status(400).send('Error parsing request');
|
|
}
|
|
next(null);
|
|
});
|
|
|
|
form.on('file', function (name, file) {
|
|
req.files[name] = file;
|
|
});
|
|
|
|
form.on('field', function (name, value) {
|
|
req.fields[name] = value; // otherwise fields.name is an array
|
|
});
|
|
});
|
|
};
|
|
};
|
|
|