Skip to content

Instantly share code, notes, and snippets.

@jollytoad
Created December 4, 2012 08:44
Show Gist options
  • Save jollytoad/4201905 to your computer and use it in GitHub Desktop.
Save jollytoad/4201905 to your computer and use it in GitHub Desktop.
Read a File using a FileReader returning a jQuery promise
function readFile(file) {
var reader = new FileReader();
var deferred = $.Deferred();
reader.onload = function(event) {
deferred.resolve(event.target.result);
};
reader.onerror = function() {
deferred.reject(this);
};
if (/^image/.test(file.type)) {
reader.readAsDataURL(file);
} else {
reader.readAsText(file);
}
return deferred.promise();
}
@amundo
Copy link

amundo commented Nov 20, 2013

this is interesting. does the file parameter get populated straight off an reference, for instance?

@dmackerman
Copy link

Thanks for this!

@anthonyserious
Copy link

Man this is useful. Thanks.

@Globik
Copy link

Globik commented Aug 3, 2015

And how to use the Promise.all() in filereader()?

@lukrizal
Copy link

+1

@Katevorona
Copy link

Thanks so much! It really works!

@sfgannon
Copy link

Use w Promise.all like any other:

//Assuming files is object of type FileList
var promises = [];
for (var i = 0; i < files.length; i++) {
    var promise = readFile(files[i]);
    promises.push(promise);
}
Promise.all(promises).then(function(arrayOfDataUrlsAndTextStrings) {
    //Do stuff
})

@stla
Copy link

stla commented Jan 9, 2017

Exactly what I needed, thank you @jollytoad !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment