ContentDocument object does not allow insert DML operation in Salesforce, so we can upload it through the ContentVersion object, without ContentDocumentId.
After DML on ContentVersion a new version of ContentDocument will be created for us in salesforce.
The easiest way to do this is using inputFile and assign it to ContentVersion instance. Like this:
<apex:page controller="ContentController">
<apex:form>
<apex:inputFile value="{!file}" />
<apex:commandbutton action="{!upload}" value="Upload" />
</apex:form>
</apex:page>
Class:
public class ContentController {
public blob file { get; set; }
public PageReference upload() {
ContentVersion v = new ContentVersion();
v.versionData = file;
v.title = 'testing upload';
v.pathOnClient ='/somepath.txt';
insert v;
return new PageReference('/' + v.id);
}
}
If you want to share the ContentVersion file then after insert DML query the ContentDocumentId from inserted ContentVersion and use ContentDocumentLink to create association between Record and ContentVersion uploaded file.
https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_contentdocumentlink.htm
Use "LinkedEntityId" field to place the record id to which this file will be associated.
Note: LinkedEntityId - Can include Chatter users, groups, records (any that support Chatter feed tracking including custom objects), and Salesforce CRM Content libraries.
hope this helps and mark this as answer if does. Thanks
You have to populate FirstPublishLocationId
, according to ContentVersion documentation:
ID of the location where the version was first published. If the
version is first published into a user's personal library or My Files,
the field will contain the ID of the user who owns the personal
library or My Files. If the first version is published into a public
library, the field will contain the ID of that library.
This field is only set the first time a version is published via the
API. It isn't set when a version is published in Salesforce CRM
Content or uploaded in Salesforce Files or. After the version is
published, it is a read-only field.
If you don't set a FirstPublishLocationId via the API, this field
defaults to the user's personal library, unless Origin is set to H,
then this field defaults to My Files.
You can also reference Special Access Rules
section from the link above where they have listed all requirements for the users trying to publish to public library.
Best Answer
Have a look at the Content Objects Data Model for the relationship between ContentVersion and ContentDocument.
One ContentDocument can have one or more ContentVersion records. The ContentVersion contains the actual data.
Use the ContentVersion to create the new record. The Excel file data should be stored in the
VersionData
field. You will also want to set theTitle
andPathOnClient
(including the file extension) fields.The ContentDocumentLink can be used to create the link to a record that supports chatter feed tracking (including custom objects).