Reputation: 131
I would like to ask you guys, how to save output of FileReader in JavaScript to a variable, or make the function where is the FileReader return the output.
Here is also a bit of code:
HTML
<input type='file' id='inputFile'>
<button id='btn'>Save</button>
JAVASCRIPT
function imgToBase64(file_input) {
if (file_input.files && file_input.files[0]) {
var fileReader = new FileReader();
fileReader.onload = function (event) {
result = event.target.result;
return result // ???
};
fileReader.readAsDataURL(file_input.files[0]);
}
}
parameter = document.getElementById('inputFile');
btn = document.getElementById('btn');
btn.onclick = function() {
variable = imgToBase64(parameter); //in this variable I would like to store the result from that function
}
I found out that the FileReader is asynchronous and i need a callback or smth, but I don't fully understand how to do so.
Thanks
Upvotes: 1
Views: 1532
Reputation: 297
You can use AngularJS's $q promises to get the result. Just make sure to inject $q wherever you create the imgToBase64 function.
function imgToBase64(file_input) {
var deferred = $q.defer();
if (file_input.files && file_input.files[0]) {
var fileReader = new FileReader();
fileReader.onload = function (event) {
result = event.target.result;
deferred.resolve(result);
};
fileReader.readAsDataURL(file_input.files[0]);
}
return deferred.promise;
}
parameter = document.getElementById('inputFile');
btn = document.getElementById('btn');
btn.onclick = function() {
imgToBase64(parameter).then(function (result) {
variable = result;
});
}
Upvotes: 2