How to check file size before uploading in AjaxFileUpload control using C# and JavaScript in ASP.Net

Last Reply on Jun 19, 2017 10:07 AM By Indresh

Posted on Jun 19, 2017 02:57 AM

hi,

i am using this snippet https://www.aspsnippets.com/Articles/Multiple-files-upload-with-Drag-and-Drop-and-Progress-bar-using-ASPNet-AJAX-AjaxFileUpload-control.aspx

 

it works.

the only problem is that it does not have validate file size before uploading like that user can only upload max 1 mb file else it returns that the error.

 

i used file size check mudassir code but in case of ajax fileupload it does not work

 

please advice

Posted on Jun 19, 2017 10:07 AM

Hi nauna,

You can check in UploadComplete event.

Using server side

protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
    try
    {
        string savePath = MapPath("~/Images/" + e.FileName);      
        if (e.FileSize > 72000) // use same condition in client side code
        {
            return;
        }
        AjaxFileUpload1.SaveAs(savePath);
    }
    catch (Exception ex)    
    {
        throw ex;
    }
}

Using client side

<script type="text/javascript">
    function UploadComplete(sender, args) {
        var filesize = args.get_fileSize();
        var fileId = args.get_fileId();

        var status = document.getElementById('AjaxFileUpload1_FileItemStatus_' + fileId);
        var container = document.getElementById('AjaxFileUpload1_FileInfoContainer_' + fileId);


        if (filesize > 72000) { // same condition used for server side
            document.getElementById('lblStatus').innerText = "error";
            if (status.innerText) {
                status.innerText = " (Error)";
            }
            if (status.textContent) {
                status.textContent = " (Error)";
            }
            container.style.color = 'Red';
        }
    }
</script>
<cc1:AjaxFileUpload ID="AjaxFileUpload1" AllowedFileTypes="jpg,jpeg" runat="server" MaximumNumberOfFiles="4"  OnUploadComplete="AjaxFileUpload1_UploadComplete" OnClientUploadComplete="UploadComplete" />

Please refer the below link.

check file size of each file before uploading multiple files in ajaxfileupload control