How to allow only pdf files in apex:inputFile in Salesforce?

Sample Code:

Visualforce Page:
<apex:page standardController="Account" extensions="FileUploadController">
    <apex:form enctype="multipart/form-data">
        <apex:outputPanel rendered="{!refreshPage}">
           <script>
              window.top.location='/{!accountId}';
           </script>
        </apex:outputPanel>
        <apex:inputFile accept=".pdf" value="{!objAttachment.Body}" fileName="{!objAttachment.Name}"></apex:inputFile>
        <apex:commandButton value="Load File" action="{!saveFile}"/>
    </apex:form>
</apex:page>

Apex Class:
public class FileUploadController {
    
    public Id accountId { get; set; }
    public Attachment objAttachment { get; set; }
    public Boolean refreshPage { get; set; }

    public FileUploadController(ApexPages.StandardController controller) {
        
        objAttachment = new Attachment();
        accountId = controller.getId();
        refreshPage = false;

    }
           
    public void saveFile() {
        objAttachment.ParentId = accountId;
        insert objAttachment;        
        refreshPage = true;
        
    }

}
 
Output:
 

2 comments:

  1. Replies
    1. Just updated the post. You can use Choose File to select the PDF and Load File button to save/insert the attachment.

      Delete