这就是我在项目中处理这个问题的方式。这似乎是目前最好的解决方案。
api.js
var multer = require('./config/multer')();
var utils = require('./utils');
module.exports = function(app, dao) {
app.post('/docs/:system', multer, function(req, res) {
var file = req.files.documento;
if (file.truncated) {
utils.removeFile(file.path); // remove the truncated file
return res.status(413).end(); // 413 ("Request Entity Too Large")
}
...
res.status(200).send({_id : document._id});
}); ...
配置/multer.js
var multer = require('multer');
var config = require('./config')();
module.exports = function() {
return multer({ dest: config.BASE_UPLOAD_FOLDER, limits: {fileSize: config.MAX_FILE_SIZE_FOR_UPLOAD},
...
onFileSizeLimit: function (file) {
console.log('> The file size exceeds the maximum size allowed (' + config.MAX_FILE_SIZE_FOR_UPLOAD/(1024*1024) + 'MB)');
},
onFileUploadComplete: function(file) {
console.log('> File \'' + file.fieldname + '\' stored in \'' + file.path + '\'' + (file.truncated ? ' (TRUNCATED).' : '.') );
}
});
};
实用程序.js
var fs = require('fs');
var removeFile = function (filePath) {
try {
fs.unlink(filePath);
console.log('File"' + filePath + '" removed!');
} catch (err) {
...
}
};
...
exports.removeFile = removeFile;