简体   繁体   English

未使用 multer 上传/创建图像文件

[英]Image file not being uploaded/created using multer

I am building a blog site, everything is working fine except the image upload on my Post .我正在建立一个博客网站,除了在我的Post image upload外,一切正常。 The post works 100% but when i attach image it does not get uploaded or created , i don't know what i am doing wrong, please i need a help.post 100% 有效,但是当我附加image它不会被uploaded or created ,我不知道我做错了什么,请我需要帮助。 I started learning node and express few months ago.几个月前我开始学习nodeexpress Please help me.请帮我。

inside index.js file在 index.js 文件中

var multer = require('multer');
var upload = multer({dest: './uploads'});

const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;

My schema我的架构

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");
});
});

and here is my view这是我的观点

<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>

Since you're using multer with disk-storage, you need to read the image from the temporary location before storing it with mongoose.由于您将 multer 与磁盘存储一起使用,因此您需要先从临时位置读取图像,然后再将其与 mongoose 一起存储。 Besides I would change the image datatype in the mongoose schema to buffer .此外,我会将猫鼬模式中的图像数据类型更改为buffer

Something like this should work (note that I'm using async/await instead of promises directly):这样的事情应该可以工作(请注意,我使用的是 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,
...

You could also store the image as a Base64-encoded string and keep the datatype string in the schema.您还可以将图像存储为 Base64 编码的字符串,并将数据类型string保留在架构中。

EDIT:编辑:

As discussed in the comments - change the datatype of profileimage back to string as profileimage will just contain the path to the file.正如评论中所讨论的 - 将 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;
    }
    ...

Add an express middleware to serve the images, eg添加一个 express 中间件来提供图像,例如

app.use(express.static('./uploads'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM