1

I'm calling an external C# API which return me a file, that file I need to attach under Attachment.
I tried some ways but not able to get the right approach, below is the sample response from the API.

{
  "$type":"System.Byte[], mscorlib",
  "$value":"JVBERi0xLjUNCMzIDgggUi9HUzUgMTAgMCBSPj4+Pi9Hcm91cYXJlbg=="
}

Can anyone point me out to find what is the right way to process the byte array and save the file under attachment object.

  • 3
    Looks like Base64. If it is you can just put the $value into the body of an attachment and it should work. Have you tried that? I tried converting it but the mime type is of a PDF while I think the string is to short to actually be a PDf – Kasper Dec 21 '17 at 16:40
  • You're welcome, happy to help – Kasper Dec 22 '17 at 9:07
2

Whenever you see a string that is supposed to contain binary data ending in a == or = there is a very strong chance it is Base64 encoded. Those equals will be padding characters that result from 8 bit encoding to 6-bits per character.

You can easily convert a Base64 string to a Blob in Apex using EncodingUtil.base64Decode(inputString).

Blob b = EncodingUtil.base64Decode('JVBERi0xLjUNCMzIDgggUi9HUzUgMTAgMCBSPj4+Pi9Hcm91cYXJlbg==');

Attachment attachment = new Attachment();
attachment.ParentId = parentId; // Something you want to link the attachment to
attachment.Name = 'attachmentName';
attachment.Body = b;

insert(attachment);
| improve this answer | |
  • 1
    Actually I know that part, the issue was with that particular content, after conversion when I check the PDF file, it was not rendering. That's why I thought it might be different encoding. I tried this again with some other files and it start working. sometimes we really do silly mistakes to rely or try same thing recurrently. – user2809299 Dec 22 '17 at 4:59

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.