Hello friends, today we are going to discuss How to Convert String To Base64 Apex Salesforce. Base64 encoding is a method of converting binary data into a text-based format that consists of ASCII characters. This encoding is commonly used to represent binary data in contexts where only text-based data is allowed.
Base64 encoding works by dividing the binary data into groups of six bits, which are then represented as characters from a predefined set of 64 characters.
Also, check this: Phone number with Flag in LWC
Key Highlights :
- Attachment Handling: When working with attachments, such as images or documents, you may need to encode the binary data to Base64 before storing it in Salesforce.
- API Integration: Some external APIs require data to be sent in Base64 format, especially when dealing with binary data.
- Security: Base64 encoding can be used to obfuscate sensitive data in certain situations.
- Use the
Blob.valueOf(stringToEncode)
method to convert your string into a Blob. - Utilize the
EncodingUtil.base64Encode(blobToEncode)
method to get the Base64 representation.
Code :
Base64Converter.cls :
public class Base64Converter { public static String convertToBase64(String inputString) { // Convert the input string to a Blob Blob binaryData = Blob.valueOf(inputString); // Encode the Blob as a Base64 string String base64String = EncodingUtil.base64Encode(binaryData); return base64String; } }
DecodeBase64Converter.cls :
public class DecodeBase64Converter { public static String decodeBase64(String base64Content) { // decode base64 Blob blobContent = EncodingUtil.base64Decode(base64Content); // Blob to string String decodeBase64String = blobContent.toString(); return decodeBase64String; } }
Output :
Reference :
What’s your Reaction?
+1
6
+1
1
+1
+1
+1
1
+1
1