+ Start a Discussion
UmeShinUmeShin 

Upload pdf file to "file" object

How can we upload pdf file to file object using apex?

Below is what I got from other website, but there is no folder name, so how can we identify folder name?
Also, I wanna know how to get parentId.
String jsonStr = '<Base64 String>';
Attachment attach = new Attachment();
attach.contentType = 'application/pdf';
attach.name = 'myfile.pdf';
attach.parentId = '0010H00002DW2Ds';
attach.body = EncodingUtil.base64Decode(jsonStr);
insert attach;

Additionally, below is another code that I got to upload file.
ContentVersion imageData;
List<String> imageContent;
        
imageContent = getImgdata();
imageData = new ContentVersion();
imageData.ContentLocation = 'S';
imageData.PathOnClient = 'sampleData.png';
imageData.Title = imageContent[0];
imageData.VersionData = EncodingUtil.base64Decode(imageContent[1]);
insert imageData;

What is the differencen between first sample and second sample to upload file?
 
Thank you in advance.
 
Prangya JenaPrangya Jena
@UmeShin

1.Talking about the First part of code:
  a.  The Object here is 'Attachment' object. Here you can not mention any folder name.
   There is no field in the Attachment object which will refer to Folder name.
  b. The 'parentId' in 5th line is the id of the Object(standard or custom) to which the document will attach in the related List.
      E.g.- If you want attachment to be in Account's related list. Then, pass AccountId in parentId.
 
String jsonStr = '<Base64 String>';
Attachment attach = new Attachment();
attach.contentType = 'application/pdf';
attach.name = 'myfile.pdf';
attach.parentId = '0010H00002DW2Ds';
attach.body = EncodingUtil.base64Decode(jsonStr);
insert attach;
2. Difference between first and second code is the second code is on ContentDocument.
   The logic here is if you are uploading a contentDocument the the document will be available in both Files and Attachments Related List of the Object.

Hope this will help you.