我试图通过模块化我的multer
模块功能来清理我的控制器,这允许我使用我的表单上传多个文件。下面给出的当前代码有效,但我想把multer函数放在一个新文件中。我假设简单地使用该函数并从另一个文件中导出它会起作用,但出于某种原因我在表单POST期间暂停了一次,尽管在{{1}的开头调用了console.log
代码。看来该代码中的某些内容正在停止进程,但不会抛出任何错误消息。有谁看到可能导致错误的原因?
Multer在路径文件中调用:
multer
/controllers/multer.js,其中包含multer代码:
var aws = require('aws-sdk');
var multer = require('multer');
var multerS3 = require('multer-s3');
var moment = require('moment');
var uploadDate = new moment().format("YYYY-MM-DD");
var s3 = new aws.S3();
var options = {
Bucket: process.env.AWS_BUCKET,
Expires: 60
};
if(app.get('env') === 'production' || app.get('env') === 'staging'){
options.ACL = 'private'
} else {
options.ACL = 'public-read'
};
//////////Multer code being called
var upload = multer({
storage: multerS3({
s3: s3,
bucket: options.Bucket,
contentType: multerS3.AUTO_CONTENT_TYPE,
acl: options.ACL,
key: function(req, file, cb){
var fileNameFormatted = file.originalname.replace(/\s+/g, '-').toLowerCase();
cb(null, req.session.organizationId + '/' + uploadDate + '/' + fileNameFormatted);
}
}),
fileFilter: function(req, file, cb){
if(!file.originalname.match(/\.(jpg|jpeg|png|gif|csv|xls|xlsb|xlsm|xlsx)$/)){
return cb('One of your selected files is not supported', false);
}
cb(null, true);
}
}).array('fileUpload', 5);
///////Post route calling multer and rest of form submission
.post(function(req, res){
upload(req, res, function(){
if(err){
console.log('Multer upload error');
req.flash('error', err);
res.redirect(req.get('referer'));
return;
}
... MORE CODE ...
})
});
导入var express = require('express');
var app = express();
var aws = require('aws-sdk');
var multer = require('multer');
var multerS3 = require('multer-s3');
var moment = require('moment');
var s3 = new aws.S3();
var uploadDate = new moment().format("YYYY-MM-DD");
var options = {
Bucket: process.env.AWS_BUCKET,
Expires: 60,
//ContentType: req.query.file_type
};
if(app.get('env') === 'production' || app.get('env') === 'staging'){
options.ACL = 'private'
} else {
options.ACL = 'public-read'
};
module.exports = {
//Annotation file upload
annotationFileUpload: function(){
multer({
storage: multerS3({
s3: s3,
bucket: options.Bucket,
contentType: multerS3.AUTO_CONTENT_TYPE,
acl: options.ACL,
key: function(req, file, cb){
console.log("key called");
var fileNameFormatted = file.originalname.replace(/\s+/g, '-').toLowerCase();
cb(null, req.session.organizationId + '/' + uploadDate + '/' + fileNameFormatted);
}
}),
fileFilter: function(req, file, cb){
console.log("file filter called");
if(!file.originalname.match(/\.(jpg|jpeg|png|gif|csv|xls|xlsb|xlsm|xlsx)$/)){
return cb('One of your selected files is not supported', false);
}
cb(null, true);
}
}).array('fileUpload', 5);
}
}
并呼叫路由:
/controller/multer
答案 0 :(得分:1)
你需要摆脱包装函数,因为multer()
返回中间件函数本身。它超时的原因是因为你正在调用一个只创建中间件的函数并立即丢弃它,然后不做任何其他操作(比如响应请求)。
所以改变这个:
annotationFileUpload: function(){
multer({
// ...
}).array('fileUpload', 5);
}
到此:
annotationFileUpload: multer({
// ...
}).array('fileUpload', 5)