[SalesForce] Need to restrict extension using jquery

I am working on Visualforce Site. I am using to attach the attachment in contact. I want to restrict the user to attach only image, PDF or .jpg file at client side. How can I do this using jquery?

Here are my inputfile fields:

<apex:inputFile id="atchmntA" value="{!attachment1.body}" filename="{!attachment1.name}" title="Please select the files to upload"/>

<apex:inputFile id="atchmntB" value="{!attachment2.body}" filename="{!attachment2.name}" title="Please select the files to upload"/>

On save button I am already calling a javascript function in which I can add the code to restrict user to upload certain kind of files only.
Please help!!

Thanks you in advance!!

Best Answer

The following JavaScript function can be used to validate that the type of file that a user tries to upload is of a certain format. It does this by checking that the files extention (eg .jpg) is in an array of allowed extensions that is passed to the function as an argument.

VF Page

<apex:page standardController="Document" extensions="documentExt">
  <script type="text/javascript">
    function TestFileType(elemid,fileName, fileTypes) {
        if (!fileName) return;
        dots = fileName.split(".")
        //get the part AFTER the LAST period.
        //fileType = "." + dots[dots.length - 1]; We don't need this
        //if(fileTypes.join(".").indexOf(fileType) != -1){
        if(fileTypes.indexOf(fileType) != -1){   //We don't need to add .
            //alert('That file is OK!');
        }else{
            alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
            document.getElementById(elemid).value = "";
        }
    }
  </script>
  <apex:inputFile onchange="TestFileType(this.id,this.value, ['gif', 'jpg', 'png', 'jpeg', 'pdf']);" id="atchmntA" value="{!document.body}" filename="{!document.name}" title="Please select the files to upload"/>
</apex:page>

Controller

/*** Controller ***/
public class documentExt {
    public documentExt(ApexPages.StandardController controller) {
        Document d = (Document) controller.getRecord();
        d.folderid = UserInfo.getUserId(); //this puts it in My Personal Documents
    }                 
}
Related Topic