Image not showing in angular

733 Views Asked by At

When I'm testing my API from postman I can view my images but from my angular application, I cannot able to view images. There is no error in the console. below is my code which I tried.

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>

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

2

There are 2 best solutions below

1
j4rey On

Double check your api response to see what it is returning.

You need src to be "data:image/jpg;base64, [your byte array]"

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

Set img src from Byte Array

1
Andres Doncel On

You can try to use DomSanitizer to tell angular src value is safe. 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.