首页 > 解决方案 > 上传前在 Multer 中验证

问题描述

我试图验证我收到的 idProject 是 ObjectId 还是在使用 Multer 上传文件之前它是否存在于我的数据库中。但它会保存文件然后验证。

我试过把 app.post('/file', ()=>) 这样的索引放进去,它可以工作,但我想把它保存在 .controller.js 和 .route.js 中

const storage = multer.diskStorage({
    destination: path.resolve('./uploads'),
    filename: (req, file, cb, filename) => {
        cb(null, uuid() + path.extname(file.originalname));
    }
});
app.use(multer({storage: storage}).single('file'));

projectCtrl.addFileToProject = async (req, res) => {
    const { id } = req.params;
    await Project.findById(id)
        .then((project) => {
            if(project === null){
                res.json({
                    status: 'Fail to Add File 1'
                });
            }
            else{
                fileCtrl.uploadFile(req, async (cb) => {
                    await Project.findByIdAndUpdate(id, {$addToSet: {files: cb}})
                });
                res.json({
                    status: 'File Added to Project'
                });
            }
        })
        .catch(() => {
            res.json({
                status: 'Fail to Add File 2'
            });
        });
};

标签: node.jsexpressmongoosemulter

解决方案


使用 multer,您无法真正动态控制上传。但是,您可以将其上传到临时文件夹中,然后检查 id 是否存在。如果它存在于您的数据库中,您可以将该文件移动到另一个文件夹中,否则,删除该文件


推荐阅读