Sending image from server to use in EJS file

Making a basic blog with an admin section to learn the basics of node and express. I just implemented multer middleware to save images for a blog post to a folder ("images") on the server - not to mongo or an s3 bucket - keeping it simple for now to learn.

I am using EJS and using res.render to send and render the frontend. However, I want to put the image in the EJS file as well. I've tried simply passing in the filename like so:

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

postData being the data on the post from the mongodb collection. All this does is send the filename itself which is not helpful.

I've looked around, but don't seem to find an answer to this, or I'm over thinking this?

Here is the rest of the code for the controller:

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

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

exports.getPost = (req, res, next) => {
    const postPath =;
    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");

1 answer

  • answered 2021-11-23 01:54 devCrow

    Send the file path of the page to be rendered as data, register the image garden folder (ex: public/images) as a static folder using express.static in nodejs, and load the image when the file path is loaded in the rendering page. I think you can.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum