1

I'm trying to use the HTML5 FileReader to load a CSV file, but its onLoad function never triggers (tried with Firefox and Chrome). This is despite its result property being populated with the file's contents, its readyState being set to 2 (DONE), and its error property remaining null. It also produces no console errors. My code is below:

var reader = new FileReader();

function process_file(file) {
    reader.onError = function(evt) {upload_failed("There was an error opening your CSV file. It may be corrupted.")};
    reader.onAbort = function(evt) {upload_failed("There was an error opening your CSV file. It may be corrupted.")};
    reader.onLoad = upload_complete;
    reader.readAsText(file);
    alert('Started');
}
function upload_complete(evt) {
    alert('Complete');
    csv_data = reader.result;
    $submit_button.prop('disabled', false);
}
function upload_failed(message) {
    alert('Failed');
    $submit_button.prop('disabled', true);
    alert(message);
}

"Started" is the only alert which shows. The other properties of the reader were accessed through the Firefox console. The process_file function is run through:

<input type='file' onchange="process_file(this.files[0])" style="display: none;" accept=".csv"  "id and name etc..."/>

I would like to know what I'm doing wrong and how to have the onLoad function trigger when the file is loaded.

1 Answer 1

2

As per the FileReader docs, the callbacks are passed to onload, onprogress and onerror. You camel-cased them to onLoad, onProgress and onError.

var reader = new FileReader();

function process_file(file) {
    reader.onerror = function(evt) {upload_failed("There was an error opening your CSV file. It may be corrupted.")};
    reader.onabort = function(evt) {upload_failed("There was an error opening your CSV file. It may be corrupted.")};
    reader.onload = upload_complete;
    reader.readAsText(file);
    alert('Started');
}
Sign up to request clarification or add additional context in comments.

2 Comments

The hours I spent trawling through the web and I missed something so obvious. Thanks! Out of curiosity, why didn't what I was doing generate an error? Was it creating a new variable inside of the FileReader object?
FileReader extends Object, so you can set whatever properties you want on it. So setting onLoad didn't raise an error, it just set a property that was never used. I made this error many times with the Image and FileReader APIs, it's due to the terrible naming standardization of the various DOM and JS related APIs.

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.