html - 从http GET方法获取SVG并显示它

标签 html angular svg

我试图在我的 web 应用程序中显示一个 SVG 图像,但我没有将 SVG 作为文件“image.svg”拥有,我调用我的服务,它以 http 响应进行响应。响应如下:

"headers": {
        "access-control-allow-methods": [
            "PUT"
        ],
        "content-length": [
            "249664"
        ],
        "x-powered-by": [
            "Express"
        ],
        "content-disposition": [
            "attachment; filename=out.svg"
        ],
        "etag": [
            "W/\"3cf40-pgVjFGaVCiK8oIvC+f36ew7CrB8\""
        ],
        "access-control-allow-headers": [
            "Content-Type, Authorisation"
        ],
        "connection": [
            "keep-alive"
        ],
        "access-control-allow-origin": [
            "*"
        ],
        "date": [
            "Fri, 22 Nov 2019 14:06:47 GMT"
        ],
        "content-type": [
            "text/html; charset=utf-8"
        ]
    },
    "body": "PHN2ZyB4bWxucz0iaHR0cDovL3 [...] 5lPjwvc3ZnPg=="

我已经尝试使用具有 [data] 属性的对象标记并在该 [data] 字段中传递正文的内容,但结果并不异常(exception)(这是我的 web 应用程序,但在一个小窗口中......我不'不明白)

有没有办法在不将其下载为文件的情况下显示该 SVG?

最佳答案

您需要使用 DomSanitizer用于 sanitizer 您的 base64图片。进口 DomSanitizer并在 HTML 中使用如下,

TS

import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  // variable containing image string (base64)
  // in your case body of response
  svgData = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';

  constructor(public sanitizer: DomSanitizer) { } // inject domsanitizer
}


HTML

<img [src]="sanitizer.bypassSecurityTrustResourceUrl('data:image/svg+xml;base64, '+ svgData)">

演示 Stackblitz

关于html - 从http GET方法获取SVG并显示它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58996657/

相关文章:

html - 使用 JWPlayer 的 html5 背景视频流的最佳文件大小?

javascript - JS 正则表达式 : select only links (a) with attr

html - 如何使子div成为位置绝对父容器的100%高度

angular - RXJS 处理两个不同的事件,其中第一个事件必须取消第二个事件

java - java.util.Deque.push 上的异常 java.lang.NoSuchMethodError

html - 当父级不在 : relative 位置时定位

angular - ngrx更新数组内的对象

angular - 使用具有两列的 Angular 列表

javascript - 检查 svg 中像素图像的成功加载

html - IE11 和 Opera 上的 CSS SVG sprite 错误