Home > Back-end >  Get user imageUrl path in Angular 13
Get user imageUrl path in Angular 13

Time:08-14

How can i get the path of a file input image, i've tried with an event but im getting a fakepath, and not the path where the picture is... How can i make this work?

typescript

 this.registerForm = new FormGroup(
{
imageUrl: new FormControl('',Validators.required)
}

submitForm(user: User){
user.imageUrl = this.registerForm.get('imageUrl').value;
}

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

  reader.onload = (e: any) => {
    this.user.imageUrl = e.target.result;
  }
  reader.readAsDataURL(e.target.files[0]);
}
}

html

 <div>
        <input  type="file" (change)="fileChangeEvent($event)" formControlName="imageUrl">
        <img [src]="user.imageUrl" alt="" height="40px">
 </div>

database example

enter image description here

CodePudding user response:

first you have to add a property for viewing your Image:

imagePreview : string;

then :

 this.registerForm = new FormGroup(
{
imageUrl: new FormControl('',Validators.required)
}

and you can set the submit form later. Before submitting you can load your uploaded file like this :

    fileChangeEvent(event : Event){
        const file = (event.target as HTMLInputElement).files[0];
        this.registerForm.patchValue({imageUrl: file});
        this.registerForm.get('imageUrl').updateValueAndValidity();
        // console.log(file);
        // console.log(this.registerForm)
        const reader = new FileReader();
        reader.onload = () =>{
          this.imagePreview = reader.result as string;
        };
        reader.readAsDataURL(file);
      }

and in your html template :

  <div>
        <input  type="file" (change)="fileChangeEvent($event)"/>
         //you don't need to add formControlName for image you have already added the formGroup <form> [formGroup]="registerform"
        <img [src]="imagePreview" alt="" height="40px">
 </div>

then:

submitForm(){
console.log(this.registerForm.value.imageUrl);
}
  • Related