How to Convert String to Blob in Salesforce Apex

In Salesforce, a Blob is a collection of binary data stored as a single object. We can convert this data type to or from a String using the toString and valueOf methods, respectively.

Recently, while developing an Apex class to generate a text file with content and store it in Salesforce as an attachment or file, I realized the need to save the file as a text file and store it in Salesforce as a file attachment.

As a solution for this, I converted the String to a blob. In the steps below, I will explain how to convert a string to a blob in Salesforce Apex.

Convert String to Blob in Salesforce Apex

To convert a string to a blob in Salesforce Apex, we will use the Blob.valueof() function. I will explain the method in the steps below.

  1. Open the Apex anonymous window and enter the code below.
String blbString = 'Pdf Document';

Blob strBlob = Blob.valueOf(blbString);

System.debug('Blob length: ' + strBlob.size());
  1. After entering the code, select the checkbox Open in debug, then click on the Execute button.
    • In the Console log window, select the object to debug only. You will then see that the string is converted to a blob data type. Using the .size() function, we display the length of the blob.
Convert string to blob in Salesforce apec

In this way, we can convert the string to a blob in Salesforce Apex by using the valueOf(string) function.

By now, you will be able to convert a string data type to a blob in Salesforce Apex by using the Blob.valueOf(blbString) function.

You may also like to read.

live webinar

Build Your First Agentforce AI Agent in Salesforce

We will show demo on the complete process of building your first AI Agent in Salesforce using Agentforce. You’ll learn how agents work and how to connect your agent to Salesforce data to deliver intelligent business outcomes.

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.