Created
December 4, 2012 08:44
-
-
Save jollytoad/4201905 to your computer and use it in GitHub Desktop.
Read a File using a FileReader returning a jQuery promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
Thanks so much! It really works!
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
})
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
+1