【问题标题】:Display Images on HTML using MongoDB, But it didn't show使用 MongoDB 在 HTML 上显示图像,但没有显示
【发布时间】:2019-06-13 00:04:58
【问题描述】:

我有使用 Node.js 的代码后端和 HTML 中的前端。我试图将存储在 mongo 中的图像放到前端。但在 HTML 中它不显示图像。但是当我将图像的二进制数据粘贴到 img src 标签中时,它可以工作。请帮忙。

index.js

 function loadImages() {
    let isbn=''
    let imgSource=''
    if (CURRENT_URL.includes('#')) {
         isbn = CURRENT_URL.substr(CURRENT_URL.indexOf('#') + 1, 
  CURRENT_URL.length);
        console.log(isbn);
    }

    axios.get(baseUrlLocal + '/book/image/'+isbn)
    .then(response => {
        console.log(response.data)
    document.getElementById('imgSource')
    .setAttribute(
    'src', 'data:image/png;base64,' + 
 btoa(unescape(encodeURIComponent(response.data))) +"'"
);

    })
    .catch(err => {
        console.log(err);
    });

}

HTML

 <div class="card-body" id="image-src">
      <img id="imgSource" src="" alt="Red dot" />
</div>

【问题讨论】:

    标签: html node.js mongodb


    【解决方案1】:

    我认为你不能在 node.js 中做到这一点

        document.getElementById('imgSource')
        .setAttribute(
        'src', 'data:image/png;base64,' + 
     btoa(unescape(encodeURIComponent(response.data))) +"'"
    );
    

    文档对象在您的浏览器伴侣中可用。在 node js 中,你不能像这样使用它。如果要渲染已处理的图像,则可能需要寻找前端模板引擎 喜欢

    • ejs
    • 哈巴狗
    • 车把

    因为 ejs 的语法有点烦人,有时你可以使用像把手这样的替代方法,看看 here 把手就像一个模板引擎。如果你熟悉 Laravel 或 ASP.NET 的 Razor Blade 或 Angular 的字符串插值技术,这很像

    进入你的外壳并像这样安装把手

    npm install --save 车把

    由于这个话题有点过多,无法作为答案进行讨论,我将只为您提供this 链接,提供有关如何安装和使用把手的教程。试试那个伙伴,你将能够实现你正在寻找的东西..干杯......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      • 1970-01-01
      • 2023-01-28
      • 1970-01-01
      • 2015-04-09
      • 1970-01-01
      • 2013-11-27
      相关资源
      最近更新 更多