如何使用multer

时间:2016-07-11 17:36:38

标签: node.js express passport.js multer

我的nodejs应用程序接受来自具有快速中间件强制许可的用户的文件上传,并使用multer

典型的路由进行身份验证,检查用户是否被允许,然后进行导入,例如:

router.post('/:id/import', passport.authenticate('jwt', { session: false }), permit('admin'), function(req, res, next) {
    MyClass.doImport(req.file.path).then(function(result) {
        res.json(result);
    }).catch(function(error) {
        res.status(500).json(error);
    });
});

如果没有错误,这很有用,导入功能会删除该文件。但是如果出现错误(如无效或不允许的用户),则会创建上传的文件并将其保留在磁盘上。

在所有权限中间件成功运行之前,我不想在磁盘上创建任何文件。我尝试使用multer作为链的最后端,即:

var app = express();

app.use( // ...

app.use(passport.initialize());
app.use(multer({dest:'./tmp/'}).single('file'));

但是在auth错误中,我仍然以tmp中的文件结束。

如果所有其他中间件都通过,我怎么能避免在磁盘上创建文件?

如果不可能,我是否可以添加一个中间件功能,该功能仅在存在文件附件且上游出现错误时才会运行?

2 个答案:

答案 0 :(得分:2)

Move your multer middleware so that it gets executed only right before the relevant route handler(s). That way if any other middleware "rejects" the request, you do not have temporary files left over. For example:

function isLoggedIn(req, res, next) {
  if (req.isAuthenticated())
    return next();
  res.redirect('/');
}
var fileUpload = multer({dest:'./tmp/'}).single('file');

var app = express();
// ...
app.use(passport.initialize());
// ...
app.put('/upload', isLoggedIn, fileUpload, function(req, res) {
  // use `req.file`
});

答案 1 :(得分:0)

您还可以使用cron和' fs'的组合。模块定期执行此任务。你只需要将这段代码放在app.js中。 我必须定期删除所有临时文件和文件夹。

var fs = require('fs');
var CronJob = require('cron').CronJob;
var temp_folder_path = path.join(__dirname, 'public', 'uploads');

     /*
        Seconds: 0-59
        Minutes: 0-59
        Hours: 0-23
        Day of Month: 1-31
        Months: 0-11
        Day of Week: 0-6 // 0 = Sunday
       * cronjob for deleting temp files from public/upload folders
       * this cronjob runs from Monday through Friday at midnight 12:00 
    */
    new CronJob('00 00 00 * * 1-5', function () {
    console.log('deleting all temporary file from public/uploads/*');
    deleteFolderRecursive(temp_folder_path)
}, null, true, 'America/Los_Angeles');


// Used for deleting all files and sub-folders from 'public/upload/*'
// Multer : stores temporary files in this folder
var deleteFolderRecursive = function (path) {
    if (fs.existsSync(path)) {
        fs.readdirSync(path).forEach(function (file, index) {
            var curPath = path + "/" + file;
             if (fs.lstatSync(curPath).isDirectory()) { // recurse
                deleteFolderRecursive(curPath);
                fs.rmdirSync(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
    }
};