首页 > 解决方案 > 访问 Multer.diskStorage->filename 中的 res.locals

问题描述

我正在登录,其中使用由 userImage、userName、userStatus 组成(全部作为表单数据发送)。使用 Multer 上传 userImage 即时消息。这就是我的路线的样子

router.post('/create', upload.any(), createUser, upload.single('userImage'));

upload.any()这个即时通讯调用,以便我可以从表单数据主体中检索用户名和用户状态,否则无法通过req.body其他方式访问

createUser是我的中间件来创建看起来像这样的用户吗

        var savedUser = await user.save();
        var createdUserId = savedUser._id;  // use this to add to the profile Image's name 

        var imgExtension = path.extname(req.body.userImage)
        var imgPath = `./images/profileImages/${createdUserId}_profileImage${imgExtension}`
        
        //now update the newly created user with its image 
        await userModel.updateOne({_id: createdUserId},{
            image: {
                path: imgPath,
                contentType: `image/${imgExtension}`  
            }
        });
        // to use in Multer middleware
        res.locals.imgName = String(`${createdUserId}_profileImage${imgExtension}`)

        res.status(201).json({
            message: "User has been saved",
            userId: createdUserId
        });        
        
        next()

所以我使用 mongoDB,在数据库中创建用户后,我得到了我想要包含在图像名称中的 ObjectID,只有图像的路径被保存在服务器上。

现在我正在尝试将 imgName 传递res.locals.imgName给 Multer 中间件,以便我可以将其存储在服务器上。

var storage = multer.diskStorage({
    destination: (req, file, cb) =>{
        cb(null, './images/profileImages')
    },
    filename: (req , file, cb) => {
        const imgName = req.res.locals.imgName // HERE LIES THE PROBLEM
        cb(null, `${imgName}`)
    }
});
export var upload = multer({ storage: storage});

[如果我错过了代码中的错字,那只是因为我无法将其复制并粘贴到 Stackoverflow 代码字段,nodejs 需要 ` <- 这个符号以便它可以访问字符串中的变量]

所以在数据库上一切正常,所有信息都正确保存。

现在图像被保存在服务器上,但未定义,如果我在未定义之后添加 .png,我也可以查看图像。

我需要一种方法来访问res.locals.imgNameMulter 文件名中的变量。 在这里我发现了类似的东西

一位用户说res.locals.something可以通过 访问req.res,他没有说任何其他内容,所以我尝试了req.res.res.locals.imgNametoreq.res.imgName的每种组合,但它总是未定义或完全不起作用。

那么有没有办法解决这个问题,或者我必须给 MacGyver 一些解决方法。

标签: node.jsexpresspostmanmulterdio

解决方案


推荐阅读