xiotee xiotee - 1 month ago 20
TypeScript Question

Angular 2 - File upload access

<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)?

Answer

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" value="No File Selected" (change)="_onChange($event.target)">
      ...`
})
export class FileUploadComponent {

    private _onChange(target: HTMLInputElement) : void {
         if(target.files && target.files.length > 0) {
              let file : File = target.files[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);
Comments