我有带有 multer 的 Node/Express 服务器用于文件上传。表单包含 3 个字段,分别是标题、描述和图像。
从正文中的邮递员中,我选择form-data,然后传递title、description,然后传递image。
我的路线
app.post("/uploads", (req, res, next) => {
upload.single("photo")(req, res, (err) => {
const { title, description } = req.body;
if (!title || !description) {
return res
.status(400)
.json({ error: "Title and description are required" });
}
if (err) {
return res.status(400).json({ error: err.message });
}
if (!req.file) {
console.log(req.file);
return res.status(400).json({ error: "File not uploaded." });
}
res.send(req.file);
});
});
场景 1 - 给出正确的输入(标题、描述和有效图像)后,图像将被保存。
场景 2 - 当有效图像但请求中不存在标题或描述时,则只需返回错误响应,说明需要标题/描述。但是这里发送了错误响应,同时图像也上传了,我需要阻止它。
只有当 3 个输入都有效时才保存图像,否则无需保存。
Multer 似乎在标题/描述验证发生之前先保存图像。
我还尝试了另一种方法,通过添加中间件来验证标题/描述,但它也不起作用。因为我的表单数据未定义。
const validateFields = (req, res, next) => {
const { title, description } = req.body;
console.log(title + " " + description); //its undefined
if (!title || !description) {
return res.status(400).send("title and description are neededdd");
}
next();
};
app.post( "/uploads", validateFields, upload.single("photo"), async (req, res) => {
const { title, description } = req.body;
console.log(req.file);
res.send("uploaded");
}
);
Multer 配置
import multer from "multer";
import { v4 as uuidv4 } from "uuid";
import path from "path";
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "images");
},
filename: (req, file, cb) => {
cb(null, uuidv4() + "-" + Date.now() + path.extname(file.originalname));
},
});
const fileFilter = (req, file, cb) => {
const allowedFileTypes = ["image/jpeg", "image/jpg", "image/png"];
if (allowedFileTypes.includes(file.mimetype)) {
cb(null, true); // Accept the file
} else {
cb(
new Error("Invalid file type, only JPEG, JPG, and PNG is allowed!"),
false
);
}
};
const upload = multer({
storage,
fileFilter,
limits: { fileSize: 10 * 1024 * 1024 },
}); //1MB limit
export default upload;
如何处理这个问题 - 这可能吗,还是我需要使用其他替代方法来解决这个问题。
场景 2 - 当图像有效但请求中不存在标题或描述时,只需返回错误响应,说明需要标题/描述。但这里发送了错误响应,同时图像也上传了,我需要阻止它。
如果验证失败,您需要删除上传的文件。所以请尝试此代码。
app.post("/uploads", (req, res, next) => {
upload.single("photo")(req, res, (err) => {
const { title, description } = req.body;
if (!title || !description || !req.file) {
// If any of the fields are missing, delete the uploaded file (if any)
if (req.file) {
// Delete the uploaded file if it exists
fs.unlinkSync(req.file.path); // make sure to provide correct file path
}
return res.status(400).json({ error: "Title, description, and file are required" });
}
if (err) {
return res.status(400).json({ error: err.message });
}
// If all fields are validated, send the uploaded file object
res.send(req.file);
});
});
N:B :- 记得导入核心模块,即
const fs = require('fs');
到脚本顶部。
试试这个代码。我希望它能解决问题,如果没有,请告诉我。