Skip to main content
4 answers
  1. Dec 7, 2016, 7:11 AM
    Hi,

    Please go through the below code, I think it will helps for you

    public with sharing class AttachmentUploadCon {

        public String parentId { get; set; }

      public Attachment attachment {

      get {

          if (attachment == null)

            attachment = new Attachment();

          return attachment;

        }

      set;

      }

      public PageReference upload() {

        attachment.OwnerId = UserInfo.getUserId();

        attachment.ParentId = '008521547896510'; // the record the file is attached to

        attachment.IsPrivate = true;

        try {

          insert attachment;

        } catch (DMLException e) {

          ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));

          return null;

        } finally {

          attachment = new Attachment(); 

        }

        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));

        return null;

      }

    }

    <apex:page controller="AttachmentUploadController">  

      <apex:sectionHeader title="Visualforce Example" subtitle="Attachment Upload Example"/>

      <apex:form enctype="multipart/form-data">

        <apex:pageMessages />

        <apex:pageBlock title="Upload a Attachment">

          <apex:pageBlockButtons >

            <apex:commandButton action="{!upload}" value="Save"/>

          </apex:pageBlockButtons>

          <apex:pageBlockSection showHeader="false" columns="2" id="block1">

            <apex:pageBlockSectionItem >

              <apex:outputLabel value="File Name" for="fileName"/>

              <apex:inputText value="{!attachment.name}" id="fileName"/>

            </apex:pageBlockSectionItem>

            <apex:pageBlockSectionItem >

              <apex:outputLabel value="File" for="file"/>

              <apex:inputFile value="{!attachment.body}" filename="{!attachment.name}" id="file"/>

            </apex:pageBlockSectionItem>

          </apex:pageBlockSection>

        </apex:pageBlock>

      </apex:form>

    </apex:page>

    Thanks,

    Raghavendra Reddy.D

     
0/9000