bhanu bhanu - 3 months ago 38
ASP.NET (C#) Question

How to check file size of each file before uploading multiple files in ajaxtoolkit ajaxfileupload control in asp.net?



<cc1:AjaxFileUpload ID="AjaxFileUpload1" AllowedFileTypes="jpg,jpeg"
runat="server" MaximumNumberOfFiles="4" OnUploadComplete="AjaxFileUpload1_UploadComplete"
/>


Code behind file

protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
if (e.FileSize > 10)
{
string filePath = e.FileName;
AjaxFileUpload1.SaveAs(Server.MapPath(filePath));
}
else
{

}
}


I want to check that all the files size should not exceed a particular value before the files upload event.

Answer

Try this way:

Server side:

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

and on 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" />

Hope this helps!!