Home > Software design >  Return base64 of a File object using FileReader.readAsDataURL()
Return base64 of a File object using FileReader.readAsDataURL()

Time:11-12

I have a JS File object that I need to convert in base64 value and return that value in a JSON object. I'm using FileReader.readAsDataURL() but since it's asynchronous, It seems that I don't get base64 value 'on time'. I'm calling callback function that needs obj. data value, but it's undefined.

function mapFileData(file, callback) {
    var obj = {};
        obj.name = file.filename;
        obj.size = file.fileSize;
        obj.type = file.fileType;
        obj.data = getBase64(file);
    });

    console.log(JSON.stringify(obj)); // file object with undefined 'data' value 
    callback(obj);
}

function getBase64(file) {
    var fileReader = new FileReader();
    if (file) {
        fileReader.readAsDataURL(file);
    }
    fileReader.onload = function(event) {
        return event.target.result;
    };
}

I don't really know how to make obj.data value available when I call callback(obj). Any help?

CodePudding user response:

You need to turn the callback syntax to async/await syntax, so you can await the file to be converted to base64.

For example.

async function mapFileData(file, callback) {
    var obj = {};
     const base64 = await getBase64(file);
        obj.name = file.filename;
        obj.size = file.fileSize;
        obj.type = file.fileType;
        obj.data = base64
    });

    console.log(JSON.stringify(obj)); 
    callback(obj); // it would be better to return the obj here and `await` this function in the caller, instead of using callback syntax
}

function getBase64(file) {
    var fileReader = new FileReader();
    if (file) {
        fileReader.readAsDataURL(file);
    }
    return new Promise((resolve, reject) => {
      fileReader.onload = function(event) {
        resolve(event.target.result);
      };
    })
}

Also, I suggest removing callback syntax from mapFileData function and converting it to async/await syntax too.

UPDATE This is the solution with Callback syntax.

function mapFileData(file, callback) {
    
     const base64Callback = function(res) {
        var obj = {};
        obj.name = file.filename;
        obj.size = file.fileSize;
        obj.type = file.fileType;
        obj.data = res
        console.log(JSON.stringify(obj)); 
        callback(obj);
     }
     getBase64(file, base64Callback)
}

function getBase64(file, callback) {
    var fileReader = new FileReader();
    if (file) {
      fileReader.readAsDataURL(file);
    }
    fileReader.onload = function(event) {
      callback(event.target.result);
    };
}
  • Related