简体   繁体   English

图像未以角度显示

[英]Image not showing in angular

When I'm testing my API from postman I can view my images but from my angular application, I cannot able to view images.当我从邮递员那里测试我的 API 时,我可以查看我的图像,但是从我的 angular 应用程序中,我无法查看图像。 There is no error in the console.控制台中没有错误。 below is my code which I tried.下面是我尝试过的代码。

Asp.net web API 2 Asp.net Web 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 HTML

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

component.ts组件.ts

 imageData: any[] = [];

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

service.ts服务.ts

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

console.log output console.log 输出

Double check your api response to see what it is returning.仔细检查您的 api 响应以查看它返回的内容。

You need src to be "data:image/jpg;base64, [your byte array]"你需要 src 是“data:image/jpg;base64, [你的字节数组]”

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

Set img src from Byte Array 从字节数组设置 img src

You can try to use DomSanitizer to tell angular src value is safe.您可以尝试使用 DomSanitizer 来告诉 angular src 值是安全的。 Take a look at this class from angular:从角度看这个类:

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

If you don't receive a string base64 check if the image URL is working.如果您没有收到字符串 base64,请检查图像 URL 是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM