【问题标题】:Return an image and display in UI using Web API core and Angular 7使用 Web API 核心和 Angular 7 返回图像并在 UI 中显示
【发布时间】:2019-03-24 14:27:24
【问题描述】:

我正在尝试在 UI 中显示图像。

这是我的 ASP.NET Web API 核心代码。

    [Route("{id:int}/image")]
    public async Task<IActionResult> GetImage(int id)
    {
        var data = await this.designService.GetImageAsync(id);

        byte[] result = data.Data;

        return this.File(result, "image/jpeg");
    }

我关注了这个Link 我假设上面的代码是正确的(不确定是否有更好的方法来返回图像 - 请指导我)

在组件中,我的代码如下所示。

this.service.getImageThumbnail(id).subscribe(
  baseImage => {
    this.thumbnail = baseImage;
  },
  error => (this.errorMessage = error)
);

在Service中,实现是这样的

getDesignThumbnail(id: number) {
return this.http
.get(`https://localhost:44314/api/designs/${id}/thumbnail`)
.pipe(catchError(error => this.errorHandler(error)));

}

在 HTML 中,我是这样显示的。(不确定这是否正确)

 <img width="100" height="100" data-bind="attr: { src: thumbnail }" />

我收到此错误消息

【问题讨论】:

  • 添加getImageThumbnail 实现
  • 添加逻辑

标签: angular image asp.net-web-api asp.net-core-2.0


【解决方案1】:

您可以在 Web API 中返回动态对象并更改以角度显示图像的方式。

我使用这种方式从 API 显示图像。

[Route("{id:int}/image")]
    public async Task<dynamic> GetImage(int id)
    {
        var data = await this.designService.GetImageAsync(id);

        byte[] result = data.Data;

        return new { Image = result}
    }

在服务中添加private sanitizer: DomSanitizer到构造函数。

this.service.getImageThumbnail(id).subscribe(
  baseImage => {
    let objectURL = 'data:image/png;base64,' + baseImage.Image;

    this.thumbnail = this.sanitizer.bypassSecurityTrustUrl(objectURL);
  },
  error => (this.errorMessage = error)
);

更新: 我创建了一个从 base64 格式存储的 json 文件中读取 jpeg 图像的演示。

请在data:image/pngdata:image/jpeg 中检查您的图片是否为png 或jpeg https://stackblitz.com/edit/display-image-from-api

【讨论】:

  • 仍然没有显示,是否与图像大小有关。当我在 objectURL 处放置断点时,字符串看起来很大。 objectURL 有值但缩略图为空
猜你喜欢
  • 2017-05-22
  • 2018-07-24
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 2019-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多