Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 how to get file name from input with type = file

I know there are simmilar questions but none cover the method for Angular 5 or at least not in a way that I understand it.

For my image upload system I need to know if a picture is attached to the input tag and what name the file has. Here is my code:

HTML:

<input 
  type="file" 
  [(ngModel)]="currentInput"
  (change)="onFileSelected($event)"
>

Angular:

export class ImageUpload {
    currentInput;

    onFileSelected(event) {
        console.log(this.currentInput);
    }
}

No matter if there is a file attached or not the value in "currentInput" is always undefined. How does this work with input when the type is equal to "file"?

Thanks!

like image 977
Miger Avatar asked Jul 26 '18 10:07

Miger


2 Answers

@ramesh-rajendran's answer is good. If you want the TypeScript solution:

onFileSelected(event: Event) {
    const target = event.target as HTMLInputElement;
    if (target.files && target.files.length > 0) {
        console.log(target.files[0].name);
    }
}
like image 98
Nicolas Bodin-Ripert Avatar answered Nov 02 '22 19:11

Nicolas Bodin-Ripert


Try this below way

onFileSelected(event) {
 if(event.target.files.length > 0) 
  {
    console.log(event.target.files[0].name);
  }
}
like image 30
Ramesh Rajendran Avatar answered Nov 02 '22 21:11

Ramesh Rajendran