I am new to saleforce and I used the following code to save files to the Attachment object in salesfore:

String base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8');
Attachment attach = new Attachment();
attach.ParentId = parentId;
attach.Body = EncodingUtil.base64Decode(base64Data);
attach.Name = fileName;
attach.ContentType = contentType;
attach.IsPrivate = false;
insert attach;

Now, I need to generate an url by which the files can be shared outside of the salesforce. After some googling, I found out that it can be done using ContentDistribution. And I want to generate the url in the apex class itself. I have refereed to many tutorials and no one them worked for me. So, please anyone can suggest a way to do it or point to a proper tutorial link which explains the process properly that how the shareable url is generated? I used this answer and I couldn't figure out what I should add to the ContentVersionId field. When I added attachment Id to that field, I got this error:

System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, ContentVersion ID: id value of incorrect type

So, How can I share attachments using an url?

1 Answer 1


ContentVersion is standard Object that stores file in Salesforce and very similar to attachment in the terms of structure. And you need to pass the Id of ContentVersion to create ContentDistribution. So:

  1. Instead of creating Attachment, create ContentVersion to store the file. However if you need to create only attachment then you need to create a content version as well for the same as here: Adding attachments in apex, convert the code to add Files
  2. After that you can create ContentDistribution using the ContentVersion created in last step: Is it possible to get a sharing link (to non SFDC users) from 'files'/'content' via apex?
  • thank u very much. it worked.. Apr 30, 2020 at 9:37

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.