【问题标题】:show image in angular by safe url通过安全网址以角度显示图像
【发布时间】:2020-07-08 15:56:21
【问题描述】:

我想要返回带有 blobl 请求的图像,并在 html 中显示它。

我使用此代码:

    <img [src]="ImageUrl"/>

这是 ts 代码:

private src$ = new BehaviorSubject(this.Url);
    dataUrl$ = this.src$.subscribe(url => {
        return this.imageService.GetImage(url, this.id).subscribe(data => {
            this.ImageUrl=data.changingThisBreaksApplicationSecurity;
            return data.changingThisBreaksApplicationSecurity
        })
    });

这是我的服务:

GetImage(url, id): Observable<any> {
    return this.httpClient
        .get(this.appConfig.apiEndpoint+ url + id, { responseType: 'blob' })
        .pipe(
            map(res => {
                if (res) {
                    return this.domSanitizer.bypassSecurityTrustUrl(URL.createObjectURL(res));
                }
                return null;
            })
        )
}

但是当我需要显示图像时,它会在 html 中使用此 url:

<img src="unsafe:blob:http://localhost:4200/6868babb-5ab2-491f-b519-2f2a3d0ed351">

不要给我看任何图片。

有什么问题吗?我该如何解决这个问题????

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    您好,我遇到了同样的问题,但我可以通过这种方式解决它

    在html中

      <img [src]="transform(imageURI)" />
    

    在ts中

     transform(url) {
       return this.domSanitizer.bypassSecurityTrustResourceUrl(url);
     }
    

    【讨论】:

    • 嗨阿斯坎。我认为这不是好方法,因为当我们在 html 中使用该功能时,每次我们在该页面上执行操作时,都会调用该操作而不是浏览器性能问题
    • 您是否尝试过将代码中的 bypassSecurityTrustUrl 替换为 bypassSecurityTrustResourceUrl
    【解决方案2】:

    我尝试这样,这为我解决了 我希望这对你有用

    在我的组件中

    import { OnInit, ElementRef } from '@angular/core';
    
    export class myComponent implements OnInit {
    @ViewChild('myImage', { static: false }) private myImage: ElementRef
    
    
       ngOnInit() {
       }
    
       getMyImage(url: string): void {
        this.service.getImage(url)
            .subscribe(response =>
                this.myImage.nativeElement.src = window.URL.createObjectURL(response)
            )
       }
    }
    

    为我服务

    getImage(url: string): Observable<Blob> {
        return this.http.get(`${environment.api}/file/download/` + url, {responseType: 'blob'})
    }
    

    在我的html中

     <img #myImage>
    

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 2013-11-06
      • 2021-04-29
      • 2022-12-15
      • 2020-01-05
      相关资源
      最近更新 更多