Angular 2 - File upload access

angular, file-upload, typescript

Solution

Almost the same way you would do in JavaScript.

If the above is your template for let say a component named `FileUploadComponent`, you can do something like this. Keep in mind that this is `HTML5`. So browser support is from IE10.

@Component({
   selector: 'file-upload',
   template: `
      ...
      <input type="file" class="upload" (change)="_onChange($event.target.files)">
      ...`
})
export class FileUploadComponent {

    private _onChange(files: FileList) : void {
         if(files && files.length > 0) {
              let file : File = files.item(0);
              //Now you can get
              console.log(file.name);
              console.log(file.size);
              console.log(file.type);
         }
    }

}

You can extend this functionality to load the file using the `FileReader`.

If for instance you want to read a `csv` file:

Starting of with the `file`:

let reader: FileReader = new FileReader();

reader.onload = (e) => {
  let csv: string = reader.result;
  console.log(csv);
  //From here you can either use a csv parse library, or your own
  //implementation if you know what the structure of the csv is
}

reader.readAsText(file);

Problem

``` <div class="fileUpload btn btn-primary"> <span>Choose File</span> <input id="uploadBtn" type="file" class="upload" value="No File Selected" #uploadBtn/> </div> <input id="uploadFile" placeholder="No File Chosen" disabled="disabled" value="{{uploadBtn.value}}"/> ``` How do I access the file that is uploaded by the user? How do I do this in angular and typescript as I still need to process the data in the file (e.g checking for valid file types)?

Original source