1

I am trying to upload a file with the angular/ionic framework. I've been able to piece together some rough outline on how to do it, but I'm stuck with how to get "file" from the file-input.

What I have in my view is a ViewChild matching the input element:

@ViewChild('file', { read: ElementRef }) myfile: ElementRef;
public files: Set<File> = new Set<File>();

A callback function that is called everytime the files changes:

  onFilesAdded() {
    alert(this.myfile.nativeElement.outerHTML);  
    const files: { [key: string]: File } = this.myfile.nativeElement.files;
    for (let key in files) {
      if (!isNaN(parseInt(key))) {
        this.files.add(files[key]);
        alert(key);
      }
    }
  }  

The problem with the above code is '.files'. I have tried a couple of different approaches from different sources, but there's always some element that is undefined. How can i actually access the 'files' property?

Lawrence Kok
  • 1,568
  • 11
  • 29

1 Answers1

0

Instead of using @ViewChild, pass in the element from the change event.

In the HTML:

 <input type="file" (change)="onFilesAdded($event.target.files)">

and in the TypeScript:

 onFilesAdded(files) {
    for (let key in files) {
      if (!isNaN(parseInt(key))) {
        this.files.add(files[key]);
        alert(key);
      }
    }
  }
user184994
  • 17,791
  • 1
  • 46
  • 52