Please disable your adblock and script blockers to view this page
 

jQuery to validate file extension and upload image file in asp.net C#,Vb.Net

Introduction: In previous articles i explained the Example to implement Jquery form validations and  How to Drag & drop to upload multiple files using AjaxFileUpload like Facebook in asp.net and How to maintain image on PostBack in FileUpload control in asp.net(C#,VB) and Validate and upload image files in asp.net and How to create log file to record errors and exceptions in asp.net.


validate file extension using Jquery  and upload image in asp.net
Click on image to enlarge
In this article i am going to explain with example How to validate file/image extension and upload the file using asp.net's FileUpload control. Some time it is required to restrict user to upload some type of files and allow only some specific types.E.g in this article i am allowing only .jpg, .jpeg, .png, .gif, .bmp image formats and restricting all other formats.
  • In the <HEAD> tag of design page(.aspx) write the following jQuery function to validate the file extension before uploading Image
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
    $(function () {
        $('#<%=FileUpload1.ClientID %>').change(function () {
            var ValidFileExtension = ['jpg', 'JPG', 'jpeg', 'JPEG', 'png', 'PNG', 'gif', 'GIF', 'bmp', 'BMP'];
        if ($.inArray($(this).val().split('.').pop().toLowerCase(), ValidFileExtension) == -1) {
            alert("Sorry !!! Allowed image formats are '.jpeg','.jpg', '.png', '.gif', '.bmp'");
        }
    })
})
</script>

<noscript>  <h3 style="color: #FF3300;">
Javascript is not currently enabled in your browser.<br /> You must <a href="http://support.google.com/bin/answer.py?hl=en&answer=23852" target="_blank" >enable Javascript </a> to run this web page correctly.
</h3></noscript>
  • In the <BODY> tag of design page (.aspx) Place FileUpload control and a button control as:
<fieldset style="width:350px;">
            <legend>Validate using JQuery and upload image/file in asp.net</legend> 
            <table>
                <tr>
                    <td colspan="2"><asp:FileUpload ID="FileUpload1" runat="server" /></td>                    
                </tr>
                <tr>
                    <td><asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" /></td>
                    <td>
                        <asp:Label ID="lblStatus" runat="server" Text=""></asp:Label></td>
                </tr>             
            </table>         
        </fieldset>

C#.Net Code to validate file/image extension using jQuery and upload image file in asp.net
  • In the code behind file(.aspx.cs) write the code on Upload Button’s click event as:
protected void btnUpload_Click(object sender, EventArgs e)
    {
        string filePath = string.Empty;
        try
        {
            filePath = (Server.MapPath("Images/") + Guid.NewGuid() + FileUpload1.FileName);
            FileUpload1.SaveAs(filePath);
            lblStatus.Text = "Image uploaded successfully";
            lblStatus.ForeColor = System.Drawing.Color.Green;
        }
        catch (Exception ex)
        {
            lblStatus.Text = "Image couldn't be uploaded";
            lblStatus.ForeColor = System.Drawing.Color.Red;          
        }
        finally
        {
            filePath = string.Empty;
        }      
    }

VB.Net Code to validate file/image extension using jQuery and upload image file in asp.net

In the design page (.aspx) just change the line <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" /> with the ><asp:Button ID="btnUpload" runat="server" Text="Upload" />. Rest is the same
  • In the code behind file(.aspx.vb) write the code on Upload Button’s click event as:
Protected Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
        Dim filePath As String = String.Empty
        Try
            filePath = (Server.MapPath("Images/") + Convert.ToString(Guid.NewGuid()) + FileUpload1.FileName)
            FileUpload1.SaveAs(filePath)
            lblStatus.Text = "Image uploaded successfully"
            lblStatus.ForeColor = System.Drawing.Color.Green
        Catch ex As Exception
            lblStatus.Text = "Image couldn't be uploaded"
            lblStatus.ForeColor = System.Drawing.Color.Red
        Finally
            filePath = String.Empty
        End Try
    End Sub

Note: Have you notice one thing that I have used <noscript> tag in the <Head> section. This is useful in the case if the JavaScript is disabled on the browser running the website. <noscript> tag  executes only if the javaScript is disabled in the browser. jQuery can work only if JavaScript is enabled. So this is the way to detect whether JavaScript is disables or enabled and if disabled then showing appropriate message to enable it from the browser’s setting.
You can also read my article How to enable JavaScript in asp.net using C#,VB.Net to get the detailed knowledge.
  • Now run the application, browse and select an image file with the extension other than the .jpeg, .jpg, .png, .gif, .bmp , it will show the alert message “Sorry !!! Allowed image formats are '.jpeg','.jpg', '.png', '.gif', '.bmp'". If the selected file extension is valid then image will be uploaded in the Images folder.
Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates."
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily.. ConversionConversion EmoticonEmoticon