0

I am writing a WS which gets a request base64 String & other parameters which should be used to create ContentVersion record.

I tried the following from dev console.

When I user base64Encode directly on an existing COntentVersion record's VersionData value, it works, but when I print the same String and copy+paste it in the EncodingUtil.base64Decode, it does not show the preview nor is the image saved, even though it creates a CV record.
Any ideas?

ContentVersion cv1 =[select VersionData from ContentVersion where id='0686D0000009N9WQAU'];
String bas64Encoder = EncodingUtil.base64Encode(cv.versionData);
System.debug(bas64Encoder);    
 //The below String is built by copy+pasting the output from the debug statement  
String str ='iVBORw0KGgoAAAANSUhEUgAAAlgAAAB4CAYAAAAuVYzDAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAB3RJTUUH4wURAQImnbjxTgAAAAd0RVh0QXV0aG9yAKmuzEgAAAAMdEVYdERlc2NyaXB0aW9uABMJISMAAAAKdEVYdENvcHlyaWdodACsD8w6AAAADnRFWHRDcmVhdGlvbiB0aW1lADX3DwkAAAAJdEVYdFNvZnR3YXJlAF1w/zoAAAALdEVYdERpc2NsYWltZXIAt8C0jwAAAAh0RVh0V2FybmluZwDAG+aHAAAAB3RFWHRTb3VyY2UA9f+D6wAAAAh0RVh0Q29tbWVudAD2zJa/AAAABnRFWHRUaXRsZQCo7tInAAAgAElEQVR4nOy9d3gc13m3fZ+Z7bvovRIAQYK9ixIpqlG9WMWWbLlJiiPLdqI4sRw7yZd8X5TXX974jS3JdpzYkpskl0iyo05RhaqUxCb2ToAAiN7rY'; 

ContentVersion cv = new ContentVersion(); 
cv.ContentLocation = 'S';  
**Blob fileABlob = EncodingUtil.base64Decode(str);   
//File is generated but there is nothing in it  
cv.VersionData = fileABlob;**  

**Blob fileABlob = EncodingUtil.base64Decode(bas64Encoder );  
//File is generated and can show preview too   
cv.VersionData = fileABlob;**  
cv.Title = 'anything1';
cv.PathOnClient = cv.Title + '.' + 'png'; 
insert cv; 
2

Your System.debug() output is almost certainly being truncated. Salesforce won't output multiple kilobytes of data into the log. Thus, when you copy and paste base64 data from debug logs and attempt to decode it, you obtain a partial, corrupted file.

The behavior difference you observe between the two forms of insert you're performing is due to the fact that one is using this truncated log data, while the other correctly sources a complete file's data. Secondly, your second attempt populates the PathOnClient field:

cv.Title = 'anything1';
cv.PathOnClient = cv.Title + '.' + 'png'; 

This field tells Salesforce what kind of file you've uploaded; various other type fields are inferred from the filename extension. This allows the system to treat it correctly as an image.

| improve this answer | |

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.