0

Is it possible to create documents and attachments by using Visualforce Page?
I just want to upload image in "Choose File" button(InputFile tag) Where i can save documents and attachments at the same time.

3

Yes, you can attach create documents and attachments using VF page. Sample VF page for inserting Attachment.


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

  <apex:pageBlockSection columns="2">

    <apex:pageBlockSectionItem >
      <apex:outputLabel value="File Name"/>
      <apex:inputText value="{!attachment.name}"/>
    </apex:pageBlockSectionItem>

    <apex:pageBlockSectionItem >
      <apex:outputLabel value="File"/>
      <apex:inputFile value="{!attachment.body}" filename="{!attachment.name}"/>
    </apex:pageBlockSectionItem>

  </apex:pageBlockSection>
</apex:pageBlock>

Sample Controller class

public class UploadAttchCtr {

    public Attachment attachment {
        get;
        set;
    }
    public UploadAttchCtr() {
        attachment = new Attachment();
    }

    public void upload() {
    attachment.OwnerId = UserInfo.getUserId();
    attachment.ParentId = '0069000000BNuBc'; //specify the record ID;
    attachment.IsPrivate = true;

    try {
        insert attachment;
    } catch (DMLException e) {
        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Error uploading attachment'));
        //return null;
    }

    Document document = new Document();
    document.AuthorId = UserInfo.getUserId();
    document.FolderId = UserInfo.getUserId(); // put it in running user's folder
    document.Body = attachment.body;
    document.Name = attachment.Name;        
    try {
      insert document;
    } catch (DMLException e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading file'));
    }
}

}
| improve this answer | |
  • Himanshu you are creating attachment not document file. – user24524 Sep 16 '15 at 7:24
  • @user24524 Yes in my sample i am creating attachment. you can also add Document in the Similar manner. Use following for Documents : developer.force.com/cookbook/recipe/… – Himanshu Sep 16 '15 at 7:28
  • I mentioned in my question here i have to create document and attachment in single input file.Means I don't want to make individual file for document and attachment. – user24524 Sep 16 '15 at 7:31
  • You mean, you need to create both Attachment and Document from single input file? – Himanshu Sep 16 '15 at 7:32
  • Yes, You got it! – user24524 Sep 16 '15 at 7:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.