【问题标题】:Image not showing in angular图像未以角度显示
【发布时间】:2021-07-22 14:13:31
【问题描述】:

当我从邮递员测试我的 API 时,我可以查看我的图像,但从我的 Angular 应用程序中,我无法查看图像。控制台中没有错误。下面是我尝试过的代码。

Asp.net 网络 API 2

    [HttpGet]
        [AllowAnonymous]
        [Route("api/another")]
        public HttpResponseMessage GetFile(int productId)
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);

            IEnumerable<ProductImage> files = _context.ProductImages.Where(p => p.ProductId == productId);
            foreach (var item in files)
            {
                response.Content = new ByteArrayContent(item.Image);
                response.Content.Headers.ContentLength = item.Image.LongLength;

                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = item.Name;

                response.Content.Headers.ContentType = new MediaTypeHeaderValue(item.ContentType);
            }
            return response;
        } 

HTML

<div *ngFor="let img of imageData">
  <img [alt]="img.Name" [src]="img.Image">
</div>

component.ts

 imageData: any[] = [];

  getImages() {
   this.image.getProduct().subscribe(res => {
   this.imageData = [res];
   console.log(res);
  });
 }

service.ts

  getProduct() {
    return this.http
      .get(this.apiUrl + 'another?' + 'productId=' + 2, {responseType: 'blob'})
      .pipe(
        retry(2),
        catchError(this.handleError),
      );
  } 

console.log output

【问题讨论】:

  • 显而易见的问题:您确定要形成图像的完整路径吗?我没有看到传递给src 属性的 API 路径的完整路径。
  • 在您的 API 中,您只返回一个图像。是的,您创建了一个循环,但在每个循环中您都会覆盖内容:response.Content = new ByteArrayContent(item.Image);,因此您只能获得最后一张图像。您需要在 API 中创建一个返回“文件”的函数并使用 forkJoin 获取图像(或直接用作 src)
  • @Eliseo 你能帮我解决这个问题吗?

标签: angular asp.net-web-api angular11 ng-file-upload


【解决方案1】:

仔细检查您的 api 响应以查看它返回的内容。

您需要 src 为 "data:image/jpg;base64, [your byte array]"

<img src="data:image/jpg;base64, [your byte array]">

Set img src from Byte Array

【讨论】:

  • 您的答案仅适用于内联 base-64 编码图像。我在示例代码中没有看到任何暗示 API 使用 base-64 编码的内容。
【解决方案2】:

您可以尝试使用 DomSanitizer 来告诉 angular src 值是安全的。从角度看一下这个类:

this.image= this._sanitizer.bypassSecurityTrustResourceUrl('data:image/jpg;base64,' 
                 + yourBase64String);

如果您没有收到 base64 字符串,请检查图像 URL 是否正常工作。

【讨论】:

  • 你能解释一下我如何使用它吗?我没有得到
猜你喜欢
  • 1970-01-01
  • 2022-01-26
  • 2021-04-29
  • 2022-12-15
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 2017-08-22
  • 1970-01-01
相关资源
最近更新 更多