Express应用可选图片上传的错误处理问题咨询
问题描述
我尝试在Express应用中添加可选图片上传功能,但根据当前应用设计,系统似乎试图从请求体中获取图片名称,而非使用我单独编写的上传函数。请问是否有无需修改模型即可验证文件的解决方法?
当前使用的路由代码如下:
posts.post("/", async (req, res) => { const postId = uuidv1(); const userId = req.query.userId; let checkUser = await User.getById(userId); if(checkUser.length === 0) { User.create(userId); } const dateCreated = new Date().toLocaleString('en-GB'); const dateUpdated = dateCreated; let bodyValues = []; let invalid = false; let picUpload; if (req.files === undefined || req.files === null) { picUpload = 'none'; } else { picUpload = req.files.image; picUpload.mv('./images' + picUpload.name); } Post.fillable_properties.map(function (v) { if (req.body[v] === null || req.body[v] === undefined) invalid = true; else bodyValues.push(req.body[v]); }); bodyValues = [postId, ...bodyValues, picUpload, userId, dateUpdated, dateCreated]; if (!invalid) { const [results, error] = await Post.create(bodyValues); if (error.length == 0 && results.affectedRows == 1) res.status(201).json(response.prepare(201, results, error)); else res.status(400).json(response.prepare(400, results, error)); } else { res.status(400).json(response.prepare(400, [], [{ "message": "Missing data" }, bodyValues])); } });
目前代码会将invalid设为true,原因可能是图片不在请求体中,但我不知道该如何处理。
解决方案
问题核心是你遍历Post.fillable_properties时,把图片字段当成了必填的请求体参数,但图片是通过req.files获取的,不在req.body里,所以触发了invalid = true。不用修改模型的话,可按以下方式调整:
- 在遍历校验
fillable_properties时,跳过图片字段的校验 - 若需验证图片合法性(格式、大小等),直接在处理
req.files的逻辑中添加校验
具体修改后的代码如下:
posts.post("/", async (req, res) => { const postId = uuidv1(); const userId = req.query.userId; let checkUser = await User.getById(userId); if(checkUser.length === 0) { User.create(userId); } const dateCreated = new Date().toLocaleString('en-GB'); const dateUpdated = dateCreated; let bodyValues = []; let invalid = false; let picUpload; if (req.files === undefined || req.files === null) { picUpload = 'none'; } else { picUpload = req.files.image; // 可选:添加图片格式/大小校验 const allowedTypes = ['image/jpeg', 'image/png']; if (!allowedTypes.includes(picUpload.mimetype)) { return res.status(400).json(response.prepare(400, [], [{ "message": "仅支持JPG/PNG格式图片" }])); } picUpload.mv('./images' + picUpload.name); } // 跳过图片字段的请求体校验(替换成你模型中对应的图片字段名) const imageField = 'image'; Post.fillable_properties.forEach(function (v) { if (v === imageField) return; if (req.body[v] === null || req.body[v] === undefined) { invalid = true; } else { bodyValues.push(req.body[v]); } }); bodyValues = [postId, ...bodyValues, picUpload, userId, dateUpdated, dateCreated]; if (!invalid) { const [results, error] = await Post.create(bodyValues); if (error.length == 0 && results.affectedRows == 1) res.status(201).json(response.prepare(201, results, error)); else res.status(400).json(response.prepare(400, results, error)); } else { res.status(400).json(response.prepare(400, [], [{ "message": "Missing data" }, bodyValues])); } });
核心改动说明:
- 遍历
fillable_properties时,跳过图片字段的校验,避免因为req.body中无该字段而标记为无效 - 可选:在处理图片上传的分支中直接添加格式/大小校验,不合法则直接返回错误,无需进入后续逻辑
内容的提问来源于stack exchange,提问作者JSbad
相关产品推荐
相关产品推荐

