How to get image and show in my page angular 6

15,429

I'm sharing my code from my project. In this example,

I have an API that im calling it with customerNumber which returns me blob type data. And I returning this data to my component from service, In my component side I'm taking that data as blob and converting it to Image type with using this.createImageFromBlob function. And finally I'm showing that image on template side by using imageToShow.photo variable in <img [src]="imageToShow.photo"> tag.

My service.ts side,

  getCustomerImages(customerNumber: number, type: string): Observable<File> {
    let result: Observable<any> = this.http
      .get(`${this.apiBaseUrl}csbins/Customer/${customerNumber}/images`, { responseType: "blob" });
    return result;
  }

My component.ts side,

  getCustomerImages() {
    this.isImageLoading = true;
    this.getCustomerImagesSubscription = this.getCustomerService.getCustomerImages(this.refNo).subscribe(
      data => {
        this.createImageFromBlob(data);
        this.isImageLoading = false;
      },
      error => {
        this.isImageLoading = false;
      });
  }

and convert blob to image here in your component,

  createImageFromBlob(image: Blob) {
    let reader = new FileReader();
    reader.addEventListener("load",
      () => {
          this.imageToShow.photo = reader.result;
      },
      false);

    if (image) {
      if (image.type !== "application/pdf")
        reader.readAsDataURL(image);
    }
  }

and my template.html side,

          <ng-template [ngIf]="imageTypeShow">
              <ng-template [ngIf]="imageToShow.photo">
                  <img [src]="imageToShow.photo" class="img-thumbnail" *ngIf="!isImageLoading;">
              </ng-template>
          </ng-template>

Feel free to ask if you don't understand any point.

Share:
15,429
Zain Khan
Author by

Zain Khan

Updated on June 04, 2022

Comments

  • Zain Khan
    Zain Khan almost 2 years

    I'm saving image from uploader into database so it's working perfect for me but the question is if I want to show that image in my website so how can I show them and also image path should be shown like src="http://www.example.com/image.png". Please give me any example/solution for it.

    TS

    imageUrl: string = "/assets/img/default-image.png";
      fileToUpload: File = null;
      constructor(private imageService: ImageUploadService) { }
    
      handleInputFile(file: FileList){
        this.fileToUpload = file.item(0);
        var reader = new FileReader();
        reader.onload = (event:any) => {
          this.imageUrl = event.target.result;
        }
        reader.readAsDataURL(this.fileToUpload);
      }
    
      OnSubmit(Caption,Image){
        this.imageService.postFile(Caption.value, this.fileToUpload).subscribe(
          data => {
            console.log("Done");
            Caption.value = "";
            Image.value = "";
          }
        );
      }
    

    Service.Ts

    postFile(caption: string, fileToUpload: File){
        const endpoint = 'http://localhost:3343/api/UploadImage';
        const formData: FormData = new FormData();
        formData.append("Image", fileToUpload, fileToUpload.name);
        formData.append("Caption", caption);
        return this.http.post(endpoint,formData);
      }
    

    HTML

    <form #imageForm="ngForm" (ngSubmit)="OnSubmit(Caption,Image)">
            <div class="input-field col s12">
              <input type="text" #Caption ngModel name="Caption" id="Caption">
              <label for="Caption">Caption</label>
            </div>
            <img [src]="imageUrl" style="width:200px;height:200px;">
            <input type="file" #Image accept="Image/*" (change)="handleInputFile($event.target.files)">
            <button class="btn waves-effect waves-light" type="submit">Submit
              <i class="material-icons right">send</i>
            </button>
          </form>