使用multer上传图片会导致其他检索到的数据无法显示在页面上

时间:2017-10-20 06:33:25

标签: node.js express multer

在我实现用户可以上传图片的功能后,新数据不会显示在页面上。我认为它必须使用enctype =" multipart-form-data" 。如果我不在表单标记中包含enctype,则图片上传功能不起作用。我该如何解决这个问题?

Modal image

app.js

app.get("/dashboard", function(req, res){
    //get all posts from database
    Post.find({}, function(err, posts){
        if(err){
            console.log(err);
        }else{
            res.render("index", {post:posts});
        }
    })
})
app.post("/dashboard", function(req, res){

    //UPLOAD IMAGE
    upload(req, res, (err) => {
        console.log(req.file)
    });
    //CREATE NEW POST
    Post.create(req.body.post, function(err, newPost){
        if(err){
            console.log(err);
        }else{
            console.log(req.body.post)
            res.redirect("/dashboard")
        }
    })

})

index.ejs

         <form action="/dashboard" method="POST" enctype="multipart/form-data">
                            <input type="text" class="form-control" name="post[title]">

                             <select class="form-control" name="post[category]">
<!--categories for posts  -->
</select>

                        <!--ALLOW USER TO UPLOAD IMAGE-->
                                <input type="file" class="form-control-file" name="image">


                        <!--ALLOW USER TO WRITE CONTENT OF POST-->
                            <textarea class="form-control" name="post[content]"></textarea>
                            <button data-dismiss="modal">Close</button>
                            <input type="submit" >
                                         </form>

index.ejs

<tbody>
                            <!--LOOPING OVER POSTS-->
                        <% post.forEach(function(post){ %>
                            <tr>
                                <td scope="row"><%= post.id %></td>
                                <td><%= post.title %></td>
                                <td><%= post.category %></td>
                                <td><%= post.date %></td>

                                <!--BUTTON TO GO TO SHOW PAGE-->
                                <td><a href="/show" class="btn btn-secondary">
                                    <i class="fa fa-angle-double-right"> Details</i>
                                </a></td>
                            </tr>
                        <% }) %>    



                        </tbody>

0 个答案:

没有答案