簡體   English   中英

圖像未以角度顯示

[英]Image not showing in angular

當我從郵遞員那里測試我的 API 時,我可以查看我的圖像,但是從我的 angular 應用程序中,我無法查看圖像。 控制台中沒有錯誤。 下面是我嘗試過的代碼。

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

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

組件.ts

 imageData: any[] = [];

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

服務.ts

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

console.log 輸出

仔細檢查您的 api 響應以查看它返回的內容。

你需要 src 是“data:image/jpg;base64, [你的字節數組]”

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

從字節數組設置 img src

您可以嘗試使用 DomSanitizer 來告訴 angular src 值是安全的。 從角度看這個類:

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

如果您沒有收到字符串 base64,請檢查圖像 URL 是否有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM