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.readAsDataURL(file);
reader.onload = function (e) {
var res = reader.result.split(',');
let fileObj = {"fileName" : file.name, "fileType" : file.type, "fileContent" : res[1]};
fileData.push(fileObj);
};
When I try to use readAsDataURL
, It breaks javascript and does not call apex function.
Best Answer
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: