Rasheed 789456
Rasheed 789456

Reputation: 13

Image Not Rendering in ejs

I have a simple app which gets heading, description and image from the user multer handle the image uploading part and I get the images in static folder called public and its sub folder uploads. Then it is toed in the database. I find it in database and try to render the image but image is not rendering. Although it is present in uploads folder but it is not rendering. Here is My code.

const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const mongoose = require("mongoose");
const multer = require("multer");
const fs = require("fs");
const path = require("path");

//APP use
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname+"./public/"));

//Multer Setup
const storage = multer.diskStorage({
    destination: "./public/uploads/",
    filename: (req, file, cb) => {
        cb(null, file.fieldname + '_' + Date.now()+path.extname(file.originalname));
    }
});
const upload = multer({ storage: storage }).single("img");




//Mongoose Setup
mongoose.connect('mongodb://localhost:27017/project-1', {useNewUrlParser: true, useUnifiedTopology: true}).then(console.log("Successfully connected to the server"));

//Routes
app.get("/", (req, res)=>{
    BlogModel.find({}, function(err, foundItem){
        if(err){
            console.log(err);
        }else{
            console.log(foundItem);
            res.render("home", {foundItem : foundItem});
        }
    })
    
});
app.get("/creat", (req, res)=>{
    res.render("creat");
});
app.post("/creat", upload ,(req, res)=>{
    const data = new BlogModel({
        heading: req.body.name,
        desc: req.body.desc,
        img: req.file.filename
    });
    data.save((err)=>{
        if(!err){
            res.redirect("/");
        }else{
            console.log(err);
        }
    });
    console.log("Successfully Submited The Form");
});


//Database Schema
const Blogschema = new mongoose.Schema({
    heading: String,
    desc: String,
    img: String
});

//Database Model
const BlogModel = new mongoose.model("Image", Blogschema);







//Listen On Port 3000
app.listen(3000, ()=>{
    console.log("Listening on port 3000");
});
<%- include('partials/header'); -%>



<% foundItem.forEach(function(item){ %>
        
    <h1><%= item.heading %></h1>
    <p><%=item.desc%></p>
    <img src="./uploads/<%=item.img%>" alt="image">

<%})%>



<%- include('partials/footer'); -%>

Here it is stored in the public Folder inside Uploads Here is the error. Sorry if the code is to long.

Upvotes: 1

Views: 845

Answers (1)

Pranavan
Pranavan

Reputation: 1395

Try adding 'public' for static folder name

app.use(express.static("public"));

Or if you want to use __dirname,

app.use(express.static(path.join(__dirname, 'public')))

Upvotes: 1

Related Questions