function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Creating an attachment object from an Apex class

Hi all,
I'm a newbie to Salesforce and intend to create an attachment object through a method in my Apex class. My code doesnt throw any error, however the attachment object does not get inserted.
Heres my code.
public void saveAttachment(){
  String encodedContentsString = System.currentPageReference().getParameters().get('fileContents');
  Id accountId = System.currentPageReference().getParameters().get('accountId');
  Attachment attachment = new Attachment();
  attachment.Body = Blob.valueOf(encodedContentsString);
  attachment.Name = String.valueOf('test.txt');
  attachment.ParentId = accountId; 
  insert attachment;
Am I missing out on anything here or is this just not the right way to create an attachment. I also pass the required parameters i.e. fileContents (this is a Base64 encoded string) and accountId (this is supposed to be the parentId for the attachment) Kindly advise.


That looks ok to me.  I've done this before and the only things I have to add are that I would also set the ContentType = 'txt' and make sure that there is text in the encodedContentsString.

Other than that it looks fine.  It is getting called, right?


use <apex:inputFile> tag