So, I'm using a FileReader
to read a user-selected file and in Chrome everything works smoothly. However, in Mozilla, the onloadstart
event is not being fired. The official page states that such event listener does exist. Am I missing something?
Here is my code:
function handleUploadFile() {
if(window.FileReader) {
const fileChooser = document.createElement('input');
fileChooser.setAttribute('type', 'file');
document.body.appendChild(fileChooser);
fileChooser.addEventListener('change', e => {
const selectedFile = e.target.files[0];
if(selectedFile) {
const filename = selectedFile.name.split('.');
const extension = filename[filename.length - 1];
if (_.indexOf(['csv', 'dat'], extension.toLowerCase()) < 0) {
alert('The file must be of type ".csv" or ".dat"');
return;
}
const f = new FileReader();
f.readAsText(selectedFile);
f.onloadstart = (ev) => {
console.log('start');
};
f.onloadend = (ev) => {
console.log('end');
const content = ev.target.result;
this.parseFile(content, selectedFile.name, extension);
};
f.onerror = (ev) => {
console.error(ev.target.error);
};
} else {
console.error('Failed to load file');
}
});
fileChooser.click();
document.body.removeChild(fileChooser);
} else {
alert('The File APIs are not fully supported by your browser.');
}
}
The onloadstart event is fired before you listen to it. So you need to change the order like this:
const f = new FileReader();
f.onloadstart = (ev) => {
console.log('start');
};
f.onloadend = (ev) => {
console.log('end');
const content = ev.target.result;
this.parseFile(content, selectedFile.name, extension);
};
f.onerror = (ev) => {
console.error(ev.target.error);
};
f.readAsText(selectedFile); //moved this line to the bottom