I am reading a file and getting binary/ UTF-8 values from the file reader javascript. I want to convert that binary String or UTF-8 String to the base 64 String using apex.

I have tried with EncodingUtil.base64Encode(Blob.valueOf(binaryString)); but it is not converting to base 64 properly hence my image is broken.

Is there any way in apex to get base 64 string?

Javascript sample :-

fileData = new Array();
var reader = new FileReader();
    reader.onload = function (e) {
    var res = reader.result.split(',');
    let fileObj = {"fileName" : file.name, "fileType" : file.type, "fileContent" : res[1]};


When I try to use readAsDataURL, It breaks javascript and does not call apex function.

1 Answer 1


You can't start with a UTF-8 string in Apex; by then, the damage has already been done by UTF-8 string conversion. Instead, use FileReader readAsDataURL to get a base-64 encoded version of the file, then send that directly to Apex. Your final Apex code should simply be:

Blob fileBody = EncodingUtil.base64Decode(base64String);
  • I have tried with FileReader.readAsDataURL also but somewhere it breaks javascript. Sometimes it works sometimes not. I am creating a JSON with that content.
    – Aakriti.G
    Commented Apr 29, 2019 at 4:41
  • 2
    @Aakriti.G readAsDataURL works just fine on all modern browsers. I've actually written a few JavaScript-based file upload components (Visualforce, Lightning), and it works just fine. We could help you pinpoint the problem if you posted more code, but I can say with confidence that readAsDataURL is the easiest way to get your binary data to Apex.
    – sfdcfox
    Commented Apr 29, 2019 at 4:45
  • I have updated my question and added a block where I am trying to read the file using FileReader and creating JSON. Most of the times, It does not call the apex function from where I am trying to pass the JSON to the apex controller.
    – Aakriti.G
    Commented Apr 29, 2019 at 4:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .