4

How would I convert CSV data stored in the VersionData field of object ContentVersion into a CSV String.

According to the documentation:

The field VersionData is of type base64

So how to I convert that into a human readable string:

String contents = (?) contentVersions[0].VersionData;

Using EncodingUtil.Base64Encode

String contents = EncodingUtil.Base64Encode(contentVersions[0].VersionData);

Does not return the CSV data, it returns this data:

T1BQT1JUVU5JVFlJRCxQ...

When I am expecting:

field1__c, field2__c, field3__c...

3 Answers 3

5

@Robs, You can convert the blob value of ContentVersion to string as below:-

ContentVersion cv=[select id,ContentDocumentId,versiondata from Contentversion where ContentDocumentId='0697E000000HW12' ];
    Blob csvFileBody =cv.VersionData;
    String csvAsString= csvFileBody.toString();
    List<String> csvFileLines= csvAsString.split('\n');
    system.debug(csvFileLines);

toString() will give the String value and and split('\n') will split those value.

You can further split as running a for loop on List you got from above code:-

 set<String> columnvalue = new set<string>();
for(Integer i=1; i<csvFileLines.size(); i++){
   string[] csvRecordData1 = csvFileLines[i].split(',');
   columnvalue.add(csvRecordData1[0]); // here 0 indicates the no. of column from which value you want to store 
}

Hope it helps you.

2
  • 1
    The documentation says VersionData is base64: developer.salesforce.com/docs/atlas.en-us.sfFieldRef.meta/… but yes .toString works, thanks
    – Robs
    Commented Sep 7, 2018 at 12:59
  • Blob is a collection of binary data stored as a single object. Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. That is why you are getting the versiondata value as T1BQT1JUVU5JVFlJRCxQ... Commented Sep 7, 2018 at 13:09
3

VersionData is a blob, You want to convert blob into actual data and not encoded base64 String data.

The way you can do it is just call the toString method on blob.

So code to convert blob to actual data is

String myString = 'StringToBlob';
Blob myBlob = Blob.valueof(myString); //Assume my blob is your versionData
System.assertEquals('StringToBlob', myBlob.toString()); //Magic happens here.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_blob.htm#apex_System_Blob_toString

1

Using EncodingUtil. Please check this code

 EncodingUtil.base64Encode(contentVersions[0].VersionData);
1
  • Thanks. I've updated the question. Any thoughts?
    – Robs
    Commented Sep 7, 2018 at 10:12

You must log in to answer this question.

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