gpt4 book ai didi

angular - 如何使用 angular 将 blob 分配给图像 src

转载 作者:行者123 更新时间:2023-12-04 12:05:53 25 4
gpt4 key购买 nike

我正在通过返回 blob 的 http 请求获取图像,我想将返回的 blob 分配给图像 src。

http 请求:

   const options = {
headers,
responseType: 'blob' as 'json'
};

return this.httpClient.get(url, options)

组件.ts
async ngOnInit() {
this.frontImageSrc = getImage()
}

async getImage() {
const image = await this.service.imageRequest(id, "front", token).toPromise();
var imageUrl = URL.createObjectURL(image)
return imageUrl
}

组件.html
  <img src={{frontImageSrc}} alt="image"/>

图像 src 未分配,在控制台中我可以看到以下内容。

blob:http://localhost:4200/f846a3aa-8cd3-4876-8dd3-972c9469feb2 14:00:00.664 unsafe:blob:http://localhost:4200/f846a3aa-8cd3-4876-8dd3-972c9469feb2:1 GET unsafe:blob:http://localhost:4200/f846a3aa-8cd3-4876-8dd3-972c9469feb2 net::ERR_UNKNOWN_URL_SCHEME

最佳答案

留言关于:unsafe stuff 意味着 angular 清理了您的 url,因为它认为它不安全。解决这个问题的最简洁的方法是引入一个管道(虽然不是必需的):像这样:

@Pipe({ name: 'safeResourceUrl' })
export class SafeUrlPipe implements PipeTransform {
constructor(private readonly sanitizer: DomSanitizer) {}

public transform(url: string): SafeResourceUrl {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}

然后在您的组件中,您可以执行以下操作:

组件.html
  <img [src]="frontImageSrc | safeResourceUrl" alt="image"/>

组件.ts
async ngOnInit() {
this.frontImageSrc = getImage()
}

async getImage() {
const image = await this.service.imageRequest(id, "front", token).toPromise();
var imageUrl = URL.createObjectURL(image)
return imageUrl
}

ngOnDestroy() {
URL.revokeObjectURL(this.imageUrl)
}

当然,您可以在 ngOnInit 中绕过相反,但使用管道更干净。此外,由于 url 是异步创建的,因此在模板中进行空检查可能是有意义的。

关于angular - 如何使用 angular 将 blob 分配给图像 src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60170651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com