Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Ajax-toolkit

Ajax File Upload With Client Side Validation

5.00/5 (1 vote)
25 Sep 2017CPOL2 min read 12.3K  
All the information regarding Ajax file upload control and validation

Introduction

I am writing this article because it has all the information to kick-start your file upload functionality using Ajax - file upload, client-side validation for type of extension allowed, maximum upload size, preview functionality for your uploaded images.

Background

AjaxFileUpload

AjaxFileUpload is an ASP.NET AJAX control that allows you to asynchronously upload files to the server.

HTTP Handlers

An ASP.NET HTTP handler is a process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files.

Using the Code

I will waste no time and provide you all the different code blocks needed for this exercise. Let's start with HTML code.

Add the below HTML in between form tag of .aspx page. Also, you need to register Ajax control toolkit DLL in the .aspx page. For the preview of the image, we used ASP image control.

ASP.NET
<asp:UpdatePanel ID="upanel" runat="server">
    <ContentTemplate>
        <asp:Image ID="imgsignature" 
        CssClass="thumbimage" runat="server" />
        <ajax:asyncfileupload id="fusignature" runat="server" 
        completebackcolor="White" width="200"
            onuploadedcomplete="fusignature_UploadedComplete" 
            allowedfiletypes="jpg,jpeg,png,gif"
            onclientuploadstarted="uploadStart" 
            onclientuploadcomplete="OnClientAsyncFileUploadComplete"
            onclientuploaderror="uploadError" />
    </ContentTemplate>
</asp:UpdatePanel>

JavaScript code:

JavaScript
function uploadStart(sender, args) {
    var filename = args.get_fileName();
    var filext = filename.substring(filename.lastIndexOf(".") + 1);
    if (filext == "jpg" || filext == "jpeg" || 
    filext == "png" || filext == "gif") {
        return true;
    }
    else {
        var err = new Error();
        err.name = 'Image Format';
        err.message = 'Only .jpg, .gif, .png, .gif files';
        throw (err);
        return false;
    }
}

Upload start function fires as soon as we browse an image in file upload control and check whether the file being uploaded is jpg, jpeg, png or gif type. If it is not, code will fire an error and this error will be handled in uploadError function.

JavaScript
function uploadError(sender, args) {
    addToClientTable("<span style='color:red;'>" + 
    args.get_errorMessage() + "</span>");
}

function addToClientTable(text) {
    var table = document.getElementById("<%= clientSide.ClientID %>");
    var row = table.insertRow(0);

    fillCell(row, 0, text);
}

function fillCell(row, cellNumber, text) {
    var cell = row.insertCell(cellNumber);
    cell.innerHTML = text;
    cell.style.borderBottom = cell.style.borderRight = "solid 1px #aaaaff";
} 

addToClientTable and fillCell function - you can write whatever code you want in uploadError function to show a formatted error message to the user.

JavaScript
function OnClientAsyncFileUploadComplete(sender, e) {
    var size = e._length;
    if (size <= 4194304) {
        var handlerPage = '<%= Page.ResolveClientUrl("~/Handler.ashx")%>';
        var src = handlerPage;
        document.getElementById('<%= imgsignature.ClientID %>').setAttribute("src", src);
        return true;
    }
    else {
        var err = new Error();
        err.name = 'Max Size';
        err.message = 'Max. size 4 MB';
        throw (err);
        return false;
    }
}

This function again validates input image for file size and display proper error message when file size exceeds 4 MB.

I am using an ashx file to show preview of the uploaded image which will be stored in session variable.

HTTP Handler Code

C#
using System.Web.SessionState;

public void ProcessRequest(HttpContext context)
{
    if (context.Request.QueryString["Type"] != null)
    {
        byte[] img = (byte[])context.Session["signatureImage"];
        context.Response.ContentType = "text/image";
        context.Response.BinaryWrite(img);
        context.Response.Flush();
    }
}

Remember to use the below attribute in form tag. As enctype is used when form submission method is post and when you have file upload control in your form, you should set its value to "multipart/form-data" which means no character is encoded.

enctype="multipart/form-data"  

References

History

  • 25th September, 2017: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)