0

I need to share files attached to an account externally via API to another Salesforce org (to recreate the files there).

In order to do this I'm trying to create a JSON file to contain the file/s first. I've tried the below, but the VersionData is not the actual data, but an internal link it seems.

How do I go about getting the file shared correctly?

contentversion a1 = [select id, fileextension, filetype, title, versiondata from contentversion
         where contentdocumentid = '9999999999999' limit 1];

Blob fileBody = a1.VersionData;
//String myblob = fileBody.toString(); //this throws an error 
String str = JSON.serializePretty(a1);
System.debug('My str: ' + str);

The fileBody.toString throws this error :

System.StringException: BLOB is not a valid UTF-8 string

This is the debug output - I was expecting the actual content of the file, not a link.

enter image description here

1 Answer 1

1

PDF files are not comprised of UTF-8 characters so

String myblob = fileBody.toString();

will fail as you noted.

You need to use the base64 version of the Blob to get a valid string

String myBlobAsBase64 = EncodingUtil.base64Encode(fileBody); 

Note that you may run out of heap so doing this work in an async transaction (12 MB of heap versus 6 MB for synchronous) may be necessary. That said, if the PDF files are big, you'll need to rethink the whole approach

3
  • Thanks, that worked to convert the VersionData :). So after converting it I build up the JSON and then I'm good to go - will test and update.
    – Irene
    Feb 25, 2022 at 21:45
  • Receiver of the JSON will need to encode the base64 data to save as a PDF.
    – cropredy
    Feb 25, 2022 at 22:04
  • Due to the heap size limits I've had to limit the size of the file shared to 4MB as the receiving Rest Resource is synchronous, and the additional fields added to the JSON obviously throws it over the 6MB limit, but it all works nicely.
    – Irene
    Mar 2, 2022 at 1:58

You must log in to answer this question.

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