【发布时间】:2020-12-08 21:13:56
【问题描述】:
我想使用 multer 将图像上传到 mongodb。这是我的代码:
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./uploads");
},
filename: function (req, file, cb) {
cb(
null,
file.fieldname + "-" + Date.now() + path.extname(file.originalname)
);
},
});
const upload = multer({
storage: storage,
});
mongoClient 内部:
client.connect((err) => {
const adminTasks = client
.db(`${process.env.DB_NAME}`)
.collection("adminTasks");
app.post("/uploadImage", upload.single("myImage"), (req, res) => {
const img = fs.readFileSync(req.file.path);
const encode_image = img.toString(base64);
// defining json obj for image
const final_image = {
contentType: req.file.mimetype,
path: req.file.path,
image: new Buffer(encode_image, "base64"),
};
// inserting image to db
userTasks.insertOne(final_image, (err, result) => {
console.log(result);
if (err) {
console.log(err);
}
console.log("saved to db");
res.contentType(final_image.contentType);
res.send(final_image.image);
});
});
});
错误是:
TypeError: Cannot read property 'path' of undefined
我已经阅读了很多关于由于 enctype="multipart/form-data" 导致问题发生的问题。但我用过这个:
<form action="http://localhost:5000/uploadImage" method="POST">
<input type="file" enctype="multipart/form-data" name="myImage" />
<input type="submit" value="upload Image" />
</form>
如何解决这个问题????
【问题讨论】:
-
不,我无法理解建议的解决方案。
标签: node.js mongodb express multer