【问题标题】:image not getting displayed on html page using sails js使用sails js的图像没有显示在html页面上
【发布时间】:2020-11-09 05:39:17
【问题描述】:

我在我的应用程序中使用sails Js 和Mongo DB。我为博客文章上传图片和内容。我将它保存在图像文件夹中。我将文件目标和内容保存到我的 mongodb。使用文件目标,我想在我的 HTML 页面中显示内容和图像。正在显示内容,但未显示图像。 控制器:

savepost:function(req,res){
        var uploadFile=req.file("image")
        uploadFile.upload({maxBytes:1000000,dirname:'../../assets/images'}, function onUploadComplete(err, files) {
            // Files will be uploaded to ./assets/images
            // Access it via localhost:1337/images/file-name
            if (err) return res.serverError(err);
            // IF ERROR Return and send 500 error
            filename=files[0].fd;
        var content=req.body.content;
        var title=req.body.title;
       Cyberblog.create({title:title,content:content,date:date,filename:filename,}).exec(function(err){
            if(err){
              console.log(err);
              message="content not saved";
                console.log(message)
              res.redirect('/newpost');
            }
            else{
     var start=filename.lastIndexOf('\\');
     fd="images/"+filename.substring(start+1)
      post={
          title:title,
          content:content,
          fd:fd,
      }
      res.view('pages/blog/blog',{post:post})
    console.log("succesfully saved")}
    }); }); },

HTML 文件:

<div class="container">
      <div class="row align-items-stretch retro-layout-2">
        <div class="col-md-4">
          <a href="single.html" class="h-entry mb-30 v-height gradient" style="background-image:url(<%= post.fd %>);">
            <div class="text">
              <h2><%= post.title %></h2>
            </div>
          </a>
        </div>
      </div>

我无法确定这是否正确 。请帮帮我。

【问题讨论】:

    标签: javascript html node.js sails.js sails-mongo


    【解决方案1】:

    如果您在 Grunt 中使用任务,当您运行 sails lift 时,/assets/images 目录将移动到 .tmp/public/images

    然后,您需要检查uploadFile.fd 的值以验证存储文件的正确目录,因为您的公共目录是.tmp/public,然后以localhost:1337/images/my-image.png 获取图像,它应该在本地目录中为@ 987654326@.

    解决后,您可以使用相对路径通过 URL 或控制器中的类似内容访问文件:

    const url = require('url')
    post.imageUrl = url.resolve(sails.config.custom.baseUrl, post.fd)
    

    然后,在视图中,使用这个值来显示图像:

    <a href="single.html" class="h-entry mb-30 v-height gradient" style="background-image:url(<%= post.imageUrl %>);">
    

    【讨论】:

      猜你喜欢
      • 2021-04-19
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 2012-12-13
      • 1970-01-01
      • 2015-04-09
      相关资源
      最近更新 更多