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

29,607

Solution 1

Try this below way

onFileSelected(event) {
 if(event.target.files.length > 0) 
  {
    console.log(event.target.files[0].name);
  }
}

Solution 2

@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);
    }
}
Share:
29,607
Miger
Author by

Miger

Updated on September 27, 2021

Comments

  • Miger
    Miger over 2 years

    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!

  • Miger
    Miger almost 6 years
    doesn't change anything
  • Miger
    Miger almost 6 years
    Thanks for the update but that was just a typo on my behalf, your solution still doesn't do anything
  • Komal
    Komal almost 6 years
    Yes data binding not supported with file input types. It need to be done using pure javascript.
  • Leonya
    Leonya over 3 years
    The event emitted from (change) handled is NOT of type [File[]] - above code doesn't output correct file in the log