node.js - 访问 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.imgName
Multer 文件名中的变量。
在这里我发现了类似的东西
一位用户说res.locals.something
可以通过 访问req.res
,他没有说任何其他内容,所以我尝试了req.res.res.locals.imgName
toreq.res.imgName
的每种组合,但它总是未定义或完全不起作用。
那么有没有办法解决这个问题,或者我必须给 MacGyver 一些解决方法。
解决方案
推荐阅读
- firebase - 如果某人的数据不包含特定密钥,我如何防止他写?
- javascript - 页面加载后,Jquery,Django,Infinite Scroll 加载其余元素
- html - 将项目与对齐内容对齐
- angular - 如何在角度使用 3rd 方节点包?
- getstream-io - 在 getstream 中聚合更新组中的活动
- php - 使用 php 发送电子邮件后无法重定向到另一个页面
- mysql - 计算具有相同 MySQL 的 3 列值的行的出现次数
- python - Python:计算数字变化的次数
- python - 将正则表达式匹配到整个字符串,而不仅仅是字符串的一部分
- ios - CAShapeLayer 出现在 Views 之前