Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
190
rated 0 times [  197] [ 7]  / answers: 1 / hits: 79489  / 11 Years ago, wed, june 12, 2013, 12:00:00

I would like to read a file and convert it into a base64 encoded string using the FileReader object. Here's the code I use :





var reader = new FileReader();
reader.onloadend = function(evt) {
// file is loaded
result_base64 = evt.target.result;
};
reader.readAsDataURL(file);




But in this case, I get the result of the conversion in the event handler (onLoadEnd event). I would like a synchronous method. Is there a way the readAsDataURL method can return directly the value of the 'result_base64' variable ?


More From » html

 Answers
15

Synchronous tasks (blocking) are generally bad. If there is no real reason to do that synchronously, I strongly recommend you to use the event callback.


Imagine your file is broken and the HTML5 api cant read, it wont give you the result. It would break your code and block the site. Or, someone could select a 10GB file, which would freeze your HTML page until the file is completely loaded. With that asynchronous event handler you are able to catch possible errors.


To work around limitations with callbacks, i use a simple trick:


var ready = false;
var result = '';

var check = function() {
if (ready === true) {
// do what you want with the result variable
return;
}
setTimeout(check, 1000);
}

check();

var reader = new FileReader();
reader.onloadend = function(evt) {
// file is loaded
result = evt.target.result;

ready = true;
};
reader.readAsDataURL(file);

the check function, checks every second if the ready flag variable is set to true. If so, you can be sure the result is available.


It may not be best practice to do so, but i made a webapp using this technique about 30 times with more than 10 setTimeouts at the same time running, and experienced no problem until now.


[#77660] Tuesday, June 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cameron

Total Points: 591
Total Questions: 112
Total Answers: 88

Location: Botswana
Member since Sat, Jan 7, 2023
1 Year ago
;