ashwin karki
ashwin karki

Reputation: 673

How to assign FileReader base64 into a variable?

I tried to print the base46 data and it is coming by:

var fileData;
var files = document.getElementById('pickUpFileAttachment').files;
if (files.length > 0) {

    var promise = getBase64(files[0]);
    promise.then(function (result) {

        fileData = result;
        console.log(result);
    });

}

function getBase64(file, onLoadCallback) {

    return new Promise(function (resolve, reject) {
        var reader = new FileReader();
        reader.onload = function () {
            resolve(reader.result);
        };
        reader.onerror = reject;
        reader.readAsDataURL(file);
    });
} 

In console.log(result) the data is present but when i assign it to fileData and try to console it after the end of getBase64() function i get undefined. How can i assign the base64 data to a variable?

console.log("displaying the 64base data");
console.log(fileData);

It just showed me undefined of fileData value. enter image description here

Upvotes: 0

Views: 875

Answers (2)

Kousher Alam
Kousher Alam

Reputation: 1055

Promise is asynchronous and it seems you want to retrieve fileData synchronously. In this case when your fileData executed but your promise does not resolve cause it asynchronous. In this case you can use await.

var fileData = await getBase64(files[0]).catch(err=>{console.log(err});

Upvotes: 2

keaukraine
keaukraine

Reputation: 5364

At the end of getBase64() function fileData is not assigned yet because at that moment .then callback of promise has not been called.

The only place where it is set and defined is in callback of promise's .then. And as you stated, you do get data in console.log(result).

You should familiarize yourself with asynchronous JS, here are some articles:

https://medium.com/codebuddies/getting-to-know-asynchronous-javascript-callbacks-promises-and-async-await-17e0673281ee

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

Upvotes: 2

Related Questions