How to check file extensions and size before uploading file on server using jQuery ?

Hello friends, In previous article we were learn Find unique distinct elements with in JSON and jQuery inArray Method today we are going to learn How we can check file extensions and file size before uploading file on server with in 5 minutes in this short article.

First we need to know about why validate a file for extensions and size at client side ? we can also upload file on server directly and check same validation at server size too.

If we will upload file directly on server it will be time consuming process for large and unexpected file. So it will definitely degrade the performance of our application.

To overcome this problem, we must apply file validation at client side.

To do so

Step 1:   Create an web application with dot net framework.

Step 2:   Add a new web form name it FileUpload.aspx

Step 3:   Add 3 HTML controls file uploader, Button and a span (you can also use asp.net controls).

Step 4:   Add jQuery.js file reference into FileUpload.aspx as follows.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUpload.aspx.cs" Inherits="SWCLASS.FileUpload" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.10.2.min.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <input type="file" id ="fileUploader" /><br />
            <span id="spnmsg" style="color:red;"></span><br />
            <input type="submit" id="btnSubmit" value="Upload" />
        </div>
    </form>
</body>
</html>

Step 5:   Add following JavaScript code to validate file extensions and file size upto 32kb in head tag as follows.

$(function () { $("#fileUploader").change(function () { // Get uploaded file extension var extension = $(this).val().split('.').pop().toLowerCase(); // Create array with the files extensions that we wish to upload var validFileExtensions = ['jpeg', 'jpg', 'png', 'gif', 'bmp']; //Check file extension in the array.if -1 that means the file extension is not in the list. if ($.inArray(extension, validFileExtensions) == -1) { $('#spnmsg').text("Failed!! Please upload jpg, jpeg, png, gif, bmp file only.").show(); // Clear fileuload control selected file $(this).replaceWith($(this).val('').clone(true)); //Disable Submit Button $('#btnSubmit').prop('disabled', true); } else { // Check and restrict the file size to 32 KB. if ($(this).get(0).files[0].size > (32768)) { $('#spnmsg').text("Failed!! Max allowed file size is 32 kb").show(); // Clear fileuload control selected file $(this).replaceWith($(this).val('').clone(true)); //Disable Submit Button $('#btnSubmit').prop('disabled', true); } else { //Clear and Hide message span $('#spnmsg').text('').hide(); //Enable Submit Button $('#btnSubmit').prop('disabled', false); } } }); });

After adding file validation script to FileUpload.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUpload.aspx.cs" Inherits="DateTimeFormatApp.FileUpload" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
$(function () { $("#fileUploader").change(function () { // Get uploaded file extension var extension = $(this).val().split('.').pop().toLowerCase(); // Create array with the files extensions that we wish to upload var validFileExtensions = ['jpeg', 'jpg', 'png', 'gif', 'bmp']; //Check file extension in the array.if -1 that means the file extension is not in the list. if ($.inArray(extension, validFileExtensions) == -1) { $('#spnmsg').text("Failed!! Please upload jpg, jpeg, png, gif, bmp file only.").show(); // Clear fileuload control selected file $(this).replaceWith($(this).val('').clone(true)); //Disable Submit Button $('#btnSubmit').prop('disabled', true); } else { // Check and restrict the file size to 32 KB. if ($(this).get(0).files[0].size > (32768)) { $('#spnmsg').text("Failed!! Max allowed file size is 32 kb").show(); // Clear fileuload control selected file $(this).replaceWith($(this).val('').clone(true)); //Disable Submit Button $('#btnSubmit').prop('disabled', true); } else { //Clear and Hide message span $('#spnmsg').text('').hide(); //Enable Submit Button $('#btnSubmit').prop('disabled', false); } } }); });     </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <input type="file" id ="fileUploader" /><br />
            <span id="spnmsg" style="color:red;"></span><br />
            <input type="submit" id="btnSubmit" value="Upload" />
        </div>
    </form>
</body>
</html>

The above code will validate file extensions jpg, jpeg, png, gif and bmp type. you can add more file extensions as per your application requirements.

Moreover It will validate file size up to 32 kb. you can extend file size more as per you application demands by replacing 32768 (32kb) with 5*1024*1024 (5MB).

If user will try to upload any other file type or file having size larger than the specified limit (32kb), then following appropriate message

Failed!! Please upload jpg, jpeg, png, gif, bmp file only.

Failed!! Max allowed file size is 32 kb.

will be displayed to user and submit button will be disabled.

When a valid file of up to specified size is uploaded then submit button will be enabled.

If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.


Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.

 
 

{{c.Content}}

Comment By: {{c.Author}}  On:   {{c.CreatedDate|date:'dd/MM/yyyy'}} / Reply


Categories