+ Start a Discussion
sravanthi_84sravanthi_84 

How to update an attachment using Apex controller?

I have uploaded an attachment to a custom object and need to retrieve the attachment to a visualforce page and should be able to update it with new attachment. The  following code inserts an attachment and the parentId for this attachment is recId1.

 

 

 public PageReference UploadFile1()
    {          
        if(fileBody1 != null && fileName1 != null)
        {
          Attachment myAttachment1  = new Attachment();
          myAttachment1.Body = fileBody1;
          myAttachment1.Name = fileName1;
          myAttachment1.ParentId =recId1;
          insert myAttachment1;
        }
        return Page.webform;
    }  
 

Can anyone tell me how to retrieve an attachment to a visualforce page and update it .

 

Thanks in advance.

Pradeep_NavatarPradeep_Navatar

Tryout the sample code given below :

 

List<Attachement> lstDoc = Database.query('SELECT d.Id, d.Name, d.Body, d.ParentId FROM Attachement d WHERE d.Name Like \'' + Userinfo.getUserName() + '%\'');

                                                if(propFileBody != null && propFileName != null )

                                                {

                                                                if(lstDoc != null && lstDoc.size() > 0 ) //Update Record

                                                                {

                                                                                lstDoc[0].Name = Userinfo.getUserName();

                                                                                lstDoc[0].Body = propFileBody;

                                                                                lstDoc[0].ParentId=UserInfo.getUserId();

                                                                                lstDoc[0].Type = propContentType.substring((propContentType.indexOf('/')+1),propContentType.length());

                                                                                system.debug('Updated*********');

                                                                                Database.SaveResult sr = Database.Update(lstDoc[0]);

                                                                }

                                                    else

                                                                {

                                                                  Attachment myAttachment1  = new Attachment();//insert record

                                                                  myAttachment1.Body = fileBody1;

                                                                  myAttachment1.Name = fileName1;

                                                                  myAttachment1.ParentId =recId1;

                                                                  insert myAttachment1;

                                                                }

 

Hope this helps.