Home > OS >  image file upload in angular
image file upload in angular

Time:10-08

I have image file upload input with preview for showing uploaded image file. There I need to handle some conditions like follow:

  1. show default image if image file is not selected and database doesn't have image, else show according images
  2. if database have image show that in preview then after file upload selected then show uploaded file in preview

I am not getting how I can handle these condition on src of img tag.

angular html code

<div class="profile_img">
    <div class="img">
        <img [src]="url?url:defaultUserProfileUrl" alt="Profile Image" class="img-fluid">
    </div>
    <div class="form-group">
        <div class="custom-file">
            <input type="file" id="myfile" name="myfile" [formControl]="profile_image" [(ngModel)]="currentInput"
            accept='image/*' (change)="onFileSelected($event)" />
        </div>
    </div>
</div>

if database image is present then I show like below:

<img [src]="userdata.profile_path?userdata.profile_path:defaultUserProfileUrl" alt="Profile Image " class="img-fluid" />

angular ts code

  url: any = [];
  defaultUserProfileUrl:string = 'assets/images/default_user_profile.png';
  onFileSelected(event) {
    console.log(event.target.files[0]);
    this.currentInput = event.target.files[0];

    if (event.target.files && event.target.files[0]) {
      var reader = new FileReader();

      reader.readAsDataURL(event.target.files[0]); // read file as data url

      reader.onload = (event) => {
        this.url = event.target.result;
      };
    }
  }

How I can handle multiple/nested if else conditions in src of image? or is there any other solution for this?

Please guide and help. Thanks in advance.

CodePudding user response:

Already you have defined a variable defaultUserProfileUrl:string = 'assets/images/default_user_profile.png';

now define one more variable as activeImageUrl = defaultUserProfileUrl:string

and inside ngOnInit() make a backend call to retrieve the image stored in the db if any and replace the activeImageUrl with the retrieved image.

And in html

<img [src]="activeImageUrl" alt="Profile Image" class="img-fluid">
  • Related