从服务器发送图像以在 EJS 文件中使用

Sending image from server to use in EJS file

制作一个带有管理部分的基本博客,以学习 node 和 express 的基础知识。我刚刚实现了 multer 中间件来将博客 post 的图像保存到服务器上的文件夹(“图像”)中 - 而不是 mongo 或 s3 存储桶 - 现在保持简单学习。

我正在使用 EJS 并使用 res.render 发送和呈现前端。但是,我也想将图像放入 EJS 文件中。我试过像这样简单地传递文件名:

res.render(path.resolve(__dirname, "../", "views", "posts.ejs"), {postData, file});

postData 是来自 mongodb 集合的 post 上的数据。这所做的只是发送文件名本身,这没有帮助。

我环顾四周,但似乎没有找到答案,或者我想多了?

控制器的其余代码如下:

const path = require("path");
const fs = require('fs');

const Post = require('../models/modelPosts');

exports.getPost = (req, res, next) => {
    const postPath = req.params.post;
    Post.findOne({ postPath: postPath }, (error, postData) => {
        if (error) { return next(error) };
        if (postData.postReadyToView == true) {

            // find the correct image
            fs.readdirSync('./images').forEach(file => {

                const stringOfFile = JSON.stringify(file);
                const stringOfPathJPEG = JSON.stringify(postPath + ".jpeg");
                const stringOfPathJPG = JSON.stringify(postPath + ".jpg");
                const stringOfPathPNG = JSON.stringify(postPath + ".png")

                // send the ejs file and image
                if (stringOfFile == stringOfPathJPEG ||
                    stringOfFile == stringOfPathJPG ||
                    stringOfFile == stringOfPathPNG) {
                    res.render(path.resolve(__dirname, "../", "views", "posts.ejs"), {
                        postData, file
                    });
                }
            })
        } else {
            res.redirect(404, "/404");
        }
    })
};

将要渲染页面的文件路径作为数据发送,在nodejs中使用express.static将图片园文件夹(ex:public/images)注册为静态文件夹,加载图片时文件路径加载在渲染页面中。我觉得你可以。