[英]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.