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

1 Answer 1

7

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);
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, man. It works. :) May I ask how do I parse the data like csv for example? Is there a utility that I need to use in Angular 2 to do this?
@xiotee I've updated my answer a little. Angular2 does not have a csv parsing utility. That's not what angular2 is for :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.