Nov 24, 2011

Checking whether a file uploaded is of .doc or .docx file format

We can use the Java Script to check whether the file uploaded is of 2003 or 2007 word format. Hence we can handle the validation in the client side.
Java Script
<script type="text/javascript" language="javascript">
   function FileFormatValidate()
   {
        var uploadControl = document.getElementById('<%=FileUpload1.ClientID%>').value;
        //Regular Expression for the fileupload control.
        var reg = /^(([a-zA-Z]:)|(file://%7b2%7d/w )/$?)(//(/w[/w].*)) (.doc|.docx|.DOC|.DOCX)$/;
        //Checking if the file is empty or not
        if (uploadControl.length > 0) 
        {
            //Checks with the control value.
            if (reg.test(uploadControl)) 
            {
                return true;
            }
           else 
            {
                //If the condition not satisfied shows error message.
                alert("Only .doc, docx files are allowed!");
                return false;
            }
         }
        else 
        {
            //If the File is Empty or No File is  selected to upload shows this 
error message.
            alert("Please select a file to Upload");
            return false;
        }
    } //End of function FileFormatValidate.
</script>
Design
<p style="height: 28px; width: 216px">
    <asp:Button ID="btn_Upload" runat="server" Height="25px" 
        onclick="btn_Upload_Click" OnClientClick="return FileFormatValidate();" Text="Upload" Width="128px" />
</p>

Hence you can validate and check the file being uploaded at the client side using this code. This can be re-used for any file formats by changing the Regular Expression.
Happy Coding!!!


1 comment:

  1. Useful info. Fortunate me I discovered your website accidentally, and I'm surprised why this twist of fate
    didn't took place in advance! I bookmarked it.

    ReplyDelete

Dear Readers,

I LOVE to hear from you! Your feedback is always appreciated. I will try to reply to your query as soon as possible.

1. Make sure to click the "Notify me" check box at the right side to be notified of follow up comments and replies.
2. Please Do Not Spam - Spam comments will be deleted immediately upon review.