# Upload file and attach it to contentDocument

I'm trying to develop a functionality that upload files and attach it to my opportunity ContentDocument (and not attachment) like my standard component do . I'm wondering when i'm saving my uploaded file in contentdocument , if i should create a version in contentversion for that file or how does it really work , in another world how i create my contentdocument object ?

I'm a beginer in salesforce and the relationship between contentdocument and contentversion is not that clear to me.

• Yes, you are heading good way, content Version is actual place where Blob files is stored, you should find some more info on various forums, but this is good way. – patryk Mar 28 at 10:40

Whenever you insert a ContentVersion, Automatically a version get inserted for the file.The number increments with each version of the document, for example, 1, 2, 3.

Use ContentVersion object to create, query, retrieve, search, edit, and update a specific version of a Salesforce CRM Content document or Salesforce file. Use the ContentDocument object to retrieve, query, update, and delete the latest version of a document, but not a content pack, in a library or a Salesforce file.

You cannot insert ContentDocument directly, As soon as you insert ContentVersion, a ContentDocument get inserted behind the scene.

Supported Calls for ContentDocument

delete(), describeLayout()describeSObjects(), query(), retrieve(), search(), undelete(), update()

Use ContentDocument object to retrieve, query, update, and delete the latest version of a document, but not a content pack, in a library or a Salesforce file. Use the ContentVersion object to create, query, retrieve, search, edit, and update a specific version of a Salesforce CRM Content document or Salesforce file.

for inserting a ContentVersion, You can use below piece of code:-

      ContentVersion ContVerFile = new ContentVersion();
ContVerFile.VersionData = Blob.valueOf('string');
ContVerFile.Title = 'title';
ContVerFile.ContentLocation= 's';
ContVerFile.PathOnClient='title.csv';
insert ContVerFile;


In order to link the file with any record, You need to insert Contentdocumentlink with linlkentityid equals to the id of the record.

Use Contentdocumentlink object to query the locations where a file is shared or query which files are linked to a particular location. For example, the following query returns a particular document shared with a Chatter group:

SELECT ContentDocument.title FROM ContentDocumentLink WHERE ContentDocumentId = '069D00000000so2' AND LinkedEntityId = '0D5000000089123'


Insertion:-

Id conDoc = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:ContVerFile.Id].ContentDocumentId;