[英]Image file not being uploaded/created using multer
我正在建立一个博客网站,除了在我的Post
image upload
外,一切正常。 该post
100% 有效,但是当我附加image
它不会被uploaded or created
,我不知道我做错了什么,请我需要帮助。 几个月前我开始学习node
和express
。 请帮我。
在 index.js 文件中
var multer = require('multer');
var upload = multer({dest: './uploads'});
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;
我的架构
const BlogPost = new Schema({
author: ObjectId,
title: String,
body: String,
profileimage: String,
date: { type: Date, default: Date.now },
comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }]
});
var Post = mongoose.model('Post', BlogPost);
router.post("/makepost", upload.single('profileimage'), (req, res) => {
var myData = new Post(req.body);
if(req.file) {
console.log('Uploading File....');
var profileimage = req.file.filename;
console.log(profileimage)
}else {
console.log('No File Uploaded....');
var profileimage = 'noimage.jpg';
}
myData.save()
.then(item => {
res.redirect('/posts');
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
这是我的观点
<form action='/makepost' method='post' enctype="multipart/form-data">
<p>Title: <input type='text' name='title' </p>
<p>Content: <input type='text' name='body' </p>
<div class="form-group"> <label>Profile Image</label><input class="form-control"
name="profileimage" type="file" />
<p><input type='submit' value='post'></p>
由于您将 multer 与磁盘存储一起使用,因此您需要先从临时位置读取图像,然后再将其与 mongoose 一起存储。 此外,我会将猫鼬模式中的图像数据类型更改为buffer
。
这样的事情应该可以工作(请注意,我使用的是 async/await 而不是直接承诺):
router.post("/makepost", upload.single('profileimage'), async (req, res) => {
const newPost = new Post(req.body);
if (req.file) {
const imgBuffer = await fs.promises.readFile(req.file.path); // TODO add error handling
newPost.profileimage = imgBuffer;
}
try {
await myData.save();
res.redirect('/posts');
}catch(err) {
res.status(400).send("unable to save to database");
}
});
// mongoose schema
...
profileimage: Buffer,
...
您还可以将图像存储为 Base64 编码的字符串,并将数据类型string
保留在架构中。
编辑:
正如评论中所讨论的 - 将 profileimage 的数据类型改回string
因为 profileimage 将只包含文件的路径。
router.post("/makepost", upload.single('profileimage'), async (req, res) => {
const newPost = new Post(req.body);
if (req.file) {
newPost.profileimage = req.file.path;
}
...
添加一个 express 中间件来提供图像,例如
app.use(express.static('./uploads'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.