How to combine multiple Blob in apex to get single Blob value

It is possible to do it by converting Blob to Hex using EncodingUtil.convertToHex() method, concat the Hex Sequence and then convert concatenated Hex string back to Blob using EncodingUtil.ConvertFromHex() method.

Blob b1 = Blob.valueOf('s1');
Blob b2 = Blob.valueOf('s2');
Blob b3 = Blob.valueOf('s3');

String combinedDataAsHex = EncodingUtil.convertToHex(b1) + EncodingUtil.convertToHex(b2) + EncodingUtil.convertToHex(b3);
Blob combinedDataAsBlob = EncodingUtil.convertFromHex(combinedDataAsHex);

Blob is a sequence of Bytes and it need to be converted to string representation for concatenation. In Apex there are only two ways to convert Blob to String, either use base64Encode or convertToHex as suggested above. base64Encode will not work in this case as base64Encode appends additional information during encoding and this causes corrupted data if two base64Encoded Blob values are combined and converted back to Blob using EncodingUtil.base64Decode() method.

Tags:

Blob

Apex