I’m trying to read a file using FileReader:
JavaScript
x
17
17
1
async readFile(event: any) {
2
var file = event.target.files[0];
3
var data:string
4
if (file) {
5
var reader:FileReader = new FileReader();
6
reader.onload = async function (evt : FileReaderEvent) {
7
data = await evt.target.result;
8
console.log(evt.target.result);
9
10
};
11
console.log(file);
12
console.log(data);
13
await reader.readAsText(file);
14
await this.processFileContent(data);
15
}
16
}
17
However, evt.target.result still gets printed after my console.log(file) call.
Does anyone know how I can obtain the result of the file and pass it to my processFileContent function?
Advertisement
Answer
Use the new read methods on the blob itself
JavaScript
1
8
1
/** @type {Event} evt */
2
async readFile (evt) {
3
const [file] = evt.target.files
4
if (!file) return
5
const data = await file.text()
6
return this.processFileContent(data)
7
}
8
Alternative:
JavaScript
1
2
1
evt.target.files[0]?.text().then(this.processFileContent)
2