I'm new at Typescript and have a syntax problem. I want to load a user selected file (not using JQuery) and print the results to the console for now. I was following some guides in JS but with no success. This is what I have so far.
index.html
<input type="file" id="file-input" >
index.ts
document.getElementById("file-input").addEventListener("change", e => {
var reader = new FileReader();
var self = this;
reader.onload = file => {
var contents: any = file.target;
self.text = contents.result;
};
console.log(self.text.toString());
}, false);
This gives the following error in the console report:
Uncaught TypeError: Cannot read property 'toString' of undefined
at HTMLInputElement.<anonymous>
I'm not quite sure how to get the text from the buffer or if I'm even setting it up correctly.
UPDATE: Current code with modifications:
document.getElementById("file-input").addEventListener("change", async (e) => {
var file = (<HTMLInputElement>e.target).files[0];
var reader = new FileReader();
reader.onload = file => {
var contents: any = file.target;
this.text = contents.result;
console.log(this.text.toString());
};
}, false);
selfvariable is unnecessary. Just usethis: that's what arrow functions allow.