【问题标题】:Angular 2 Image Url from Local Server Not Displaying in Html来自本地服务器的 Angular 2 图像 URL 未在 Html 中显示
【发布时间】:2018-01-24 17:48:41
【问题描述】:

我有一个从本地数据库检索项目的 Angular 2 应用程序。服务器存储项目的图像,数据库存储它在服务器上的存储路径。我可以毫无问题地检索所有项目,但是在显示图片时 它不会呈现,因为它显示的是 Unsafe Url。 即 192.168.0.24:1025/UploadFile/freshmilk.jpg。所以我创建了一个管道来绕过SecurityTrustUrl。之后,错误消失但仍然不显示图像。

在检查 Html 之后,图像 src 显示了图像的正确 URL,但是 当我将鼠标悬停时,它实际上在图像 URL 之前附加了 localhost:5555。问题是图像不会显示,因为 localhost:5555 已附加到图像 URL。 如何删除图片 URL 中附加的 localhost:5555?

[Localhost:5555 附加图片 URL][1]

我尝试在不使用数据绑定的情况下对服务器中的一张图像进行硬编码。这导致了猫旁边的绿色牛奶图片,而猫是来自互联网的图片网址。

这是我的代码的 Html 部分

<img src="http://192.168.0.24:1025/UploadFile/freshmilk.jpg" width="100" height="100">
<img [src]="picturetest | safeHtml" width="100" height="100">

<div class="table">
    <table class="table">
        <thead>
        <th>Picture</th>
    <th>ID</th>
    <th>Name</th>
    <th>Quantity Stored</th>
    <th>Price</th>
    <th>Purchase Count</th>
    <th>Options</th>

    </thead>`enter code here`
    <tbody>
        <tr *ngFor="let item of items.data">
            <td><img [src]="item.picture | safeHtml" width="100" height="100"></td>
            <td>{{item.itemID}}</td>
            <td>{{item.itemName}}</td>
            <td>{{item.itemQuantityStored}}</td>
            <td>{{item.itemPrice}}</td>
            <td>{{item.purchaseCount}}</td>           
        </tr>


    </tbody>
</table>

我还尝试移除管道并手动循环绕过安全性

   this.Data.getProducts().subscribe(data => {
          this.items.data=data
          console.log(this.items.data);
          for(var i=0;i<this.items.data.length;i++)
           this.items.data[i].picture=this.sanitizer.bypassSecurityTrustUrl(this.items.data[i].picture);
            console.log("latestest");

    });

【问题讨论】:

  • 如果您能更清楚地描述问题,并将代码作为文本而不是图像提供,将会很有帮助。
  • ...我还建议不要公开共享到您的服务器的真实路径...我不确定您的后端,但是以这种方式检索图像感觉有点奇怪(绝对 ip 和端口和某些文件的完整路径)...也许您应该考虑使用一些 api 或一些工具来为您提供更简单和灵活的查询,例如 Firebase ...您是否尝试过在开头放置“https://”代表图像路径的字符串?您是否在页面标题中使用了一些基本元标记?您可能不需要绑定中的插值,请尝试 src="{{item.picture}}"

标签: html angular image typescript url


【解决方案1】:

我认为您不需要在绑定中进行插值。可以看到at this plunker简单赋值,比如

src={{path}}

适用于外部文件源。

您甚至可以看到,您可能不必做一些硬核绕过安全性的事情......您可以对数据进行清理,但在这种情况下,我认为即使这样也有些矫枉过正。

我认为问题在于您存储和检索数据的方式。我建议您迁移到一些灵活的后端,例如 Firebase 并使用这些工具的全部功能,至少在您无法正确创建和维护自己的托管/api/db 之前。我完全不喜欢 666.66.0.6:4200/my/secret/path/little_pink_kitten.jpg 形式的资源路径 ...根据路径中出现的本地主机,尝试在 src url 前面加上 https:// 或 http:// / 或者...您应该能够将所有数据存储在简单的键值数据库结构中,并带有某种 api,允许您在查询中使用 ajax/promises/etc,而不仅仅是直接向服务器询问一些绝对路径。

【讨论】:

  • 非常感谢!有效。缺少的是图像 URL 开头的 http://。
猜你喜欢
  • 2015-10-10
  • 2020-02-18
  • 1970-01-01
  • 2012-12-24
  • 2021-02-23
  • 1970-01-01
  • 2018-08-17
  • 1970-01-01
  • 2012-11-30
相关资源
最近更新 更多