We have a requirement to process attachments to convert blob to base64 format. We are querying the attachment body (i.e. in blob format) and converting that into base64 format in apex class.

Below is the code for reference:

String myBodyContent = myAttachment.body.toString();
EncodingUtil.base64Encode(Blob.valueOf(myBodyContent)); // getting heap size error on this line

We thought of storing small chunks of attachment directly into base64 format rather than converting it entirely in one go. Is there any way to achieve this? Also, is there any way to store attachment contents directly into base64 in any object's field?

Note: We cannot use JavaScript in any form(Lightning component, VF page/component as this needs to be achieved only from the trigger)


Converting to base64 increases the size by 33% (4/3). If this exceeds the heap size of 6MB, you'll get this error. This limits you to processing approximately 4,500,000 actual bytes. If you use Future/Batchable/Queueable instead, you can get content up to 9,000,000 bytes instead, but you can't return the results directly to the trigger context, since it would be asynchronous. If you need to deal with files larger than that, you no longer have an option to use Apex. You would need to offload the data to a different platform somehow, such as JavaScript, Heroku, etc.

Further, converting to a string and holding that in a variable decreases the maximum size significantly:


Finally, you already have a blob in the original Body attribute, so this could be reduced to just:

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.