如何在猫鼬/节点中动态地将图像显示为帖子页面的背景图像?

这是我的第一个问题,我是Nodejs的新手。我希望有人可以帮助我。我正在使用猫鼬,节点,ejs和express创建一个简单的博客网站,我想使用多部分表单上传图像,然后将该图像保存到本地目录中,以便可以将其动态用作背景图像。个人帖子页面。我尝试过express-fileupload和Multer,但是图像无法在后台显示。但是,它已保存到本地目录。我在想什么或做错了什么?这是我的代码段:

我的服务器代码

//jshint esversion:6

const express = require("express");

const bodyParser = require("body-parser");

const ejs = require("ejs");

const mongoose = require('mongoose');

const multer  = require('multer');
const app = express();
app.set('view engine','ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
var storage = multer.diskStorage({
destination: function (req,file,cb) {
      cb(null,'public/posts');

 },filename: function (req,cb) {
     cb(null,file.fieldname + '-' + Date.now());
 }});


 const upload = multer({ storage: storage});

数据库代码:

const  PostSchema =  new mongoose.Schema({
title: String,description: String,content: String,username: String,image: String,createdAt: {
    type: Date,default: new Date()
}
});

const Post = mongoose.model("post",PostSchema);

撰写路线:

app.get("/compose",function(req,res){

res.render("compose");

});

app.post('/compose',function (req,res) {
  const post = new Post({
      title: req.body.title,username: req.body.username,content: req.body.content,image: req.file.image
      });

  post.save(function(err){

     if(!err){

      res.redirect("/");
    }
     });
  });

app.get('/post/:id',res){

const requestedPostId = req.params.id;

 Post.findOne(

  {_id: requestedPostId},function(err,foundPost) {

       if (!err) {

       res.render("post",{post: foundPost});
    }

  });
});

我的帖子的Ejs代码:

<header class="masthead" style="background-image:url('<%=post.image'%>)">

<div class="overlay"></div>

<div class="container">

  <div class="row">

    <div class="col-lg-8 col-md-10 mx-auto">

      <div class="post-heading">

        <h1><%=post.title%></h1>

        <span class="meta">Posted by

              <a href="#"><%=post.username%></a>

              on <%=post.createdAt.toDateString()%>

            </span>
      </div>

    </div>

  </div>


</div>

表格:         

      <input type="file" name="image" class="form-control-file">

    </div>

期待任何更正! 谢谢

gangan123321 回答:如何在猫鼬/节点中动态地将图像显示为帖子页面的背景图像?

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3107612.html

大家都在问