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)

2 Answers 2


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:

  • It looks like there is not a way to stream the data via the SF API, is that correct? Meaning you must load all of the data in one go as a String before decoding (and encoding)? Feb 7 at 14:11
  • @GarrettSmith correct. Apex can't stream data, and the API doesn't support chunking or ranges.
    – sfdcfox
    Feb 7 at 14:44

This document shows you how to chunk the data to upload files whose size exceed the Apex heap limit. https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_sobject_insert_update_blob.htm

  • 1
    Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
    – identigral
    Apr 17 at 15:51

You must log in to answer this question.

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