如何将Mongodb中的图像显示到index.ejs文件中

时间:2018-08-06 14:30:33

标签: node.js mongodb image file express

我已经能够将图像上传到数据库中,但是当我尝试将它们从数据库显示到客户端时,它们位于空白容器中。我已经阅读了mongo文档,但没有明确的方向来解决问题。

app.post("/books", (req, res) => {
let newBook = req.body.bookName;
let newImage = 
upload(req, res, (err) => {
    if (err) {
        res.render('books', {
            msg: err
        })
    } else {
        if (req.file == undefined) {
            res.render('books', {
                msg: "Error: No file Selected"
            });
        } else {
            res.render('books', {
                msg: "Book Uploaded",
                file: `uploads/${req.file.filename}`
            });
        }
    }

})
let newPrice = req.body.newPrice;
let newProduct = { name: newBook, image: newImage, price: newPrice };
// Create a new book and save to DB
Book.create(newBook, function (err, newBook) {
    if (err) {
        console.log(err);
    } else {
        res.redirect('/books');
    }

});

客户端

 <div class="row text-center" style="display: flex; flex-wrap: wrap;">
    <% products.forEach(function(product) { %>
        <div class="col-md-3 col-sm-6">
            <div class="thumbnail">
                <img src="<%= typeof file != 'undefined' ? file : '' %>" alt="">
                <div class="caption">
                    <h4><%= product.name %></h4>
                </div>
            </div>
        </div>

<% }) %>

0 个答案:

没有答案