我想在我的快速路线块中使用multer,即不是作为中间件。 multer配置我作为中间件工作,但我想在调用multer之前进行一些检查。
所以我试过这个,但无济于事:
/*
* Upload a file
*/
const MediaPath = "/var/tmp";
var multer = require('multer'); // Multer is for file uploading
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, MediaPath + '/' + req.params.organisation + '/' + req.params.table + '/');
},
filename: function (req, file, cb) {
// TODO - remove the time and timezone from ISO string, resolve the correct filename, create thumbnail,
var date = new Date();
cb(null, req.params.id + '.' + date.toISOString());
}
})
//var upload = multer({ storage: storage });
var upload = multer({ storage: storage }).single('file');
router.post('/file/:organisation/:table/:id', function (req, res, next){
db.resolveTableName( req )
.then( table => {
auth.authMethodTable( req )
.then( function() {
console.log('Uploading a file: ');
upload(req, res, function( err ) {
if( err ) {
console.log('Upload error' );
res.status(500).json( err );
}
console.log('Upload success' );
res.status(200).json("success");
});
})
.catch( function( error ) {
res.status(401).json('Unauthorized');
});
})
.catch( function(e) {
res.status(400).json('Bad request');
});
});
有趣的是我没有收到错误,所以返回了200,但我没有上传文件。
有什么想法吗?
答案 0 :(得分:2)
通过将我的控件移动到中间件以在multer之前调用来修复它,因此我可以使用multer作为中间件(受此评论Nodejs Express 4 Multer | Stop file upload if user not authorized的启发):
var preUpload = function( req, res, next ) {
db.resolveTableName( req )
.then( table => {
auth.authMethodTable( req )
.then( function() {
next();
})
.catch( function( error ) {
res.status(401).json('Unauthorized');
});
})
.catch( function(e) {
res.status(400).json('Bad request');
});
};
router.post('/file/:organisation/:table/:id', preUpload, upload.single('file'), function (req, res, next){
console.log(req.body, 'Body');
console.log(req.file, 'files');
res.end();
});