Search code examples
asp.netajaxfile-uploadajaxcontroltoolkitfilesize

How to restrict file size when using AjaxFileUpload and how to communicate that to user using client javascript


We have an aspx page with AjaxFileUpload extender, which is used to asynchronously upload some image files to server.

<asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server" 
                    OnUploadComplete="UploadComplete"  
                    OnClientUploadComplete="UploadCompleteClient" /

>

And we have to keep the file size of uploaded file to a certain limit. for that we are currently using the following code on serverside as

protected void UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        if (e.FileSize <= fileSizeLimit)
        {
            AjaxFileUpload1.SaveAs(filePath);
        }
    }

and on client side as

function UploadCompleteClient(sender, args) {
        if (parseInt(args._fileSize) > fileSizeLimit) {
            alert("file exceeds file size limit");
        }

Now when a file is above the "fileSizeLimit" file is not saved on server. And client side alert show the user that file size is exceeded. But the issue now is AjaxFileUpload extender status messages show all file are uploaded successfully.

Is there anyway we can show alert error message and show proper AjaxFileUpload extender status messages

Thanks in advance


Solution

  • You can use UploadCompleteClient in client side to check if file size is exceeded, then show error message. Following is the js for this.

    <script type="text/javascript">
    function UploadCompleteClient(sender, args) {
      var filesize = args.get_fileSize();
      var fileId = args.get_fileId();
    
    
      var status = document.getElementById('AjaxFileUpload1_FileItemStatus_' + fileId);
    
      if (parseInt(filesize) > fileSizeLimit) {
    
        alert("file exceeds file size limit");
        if (status.innerText) {
          status.innerText = " file exceeds file size limit ";
        }
        if (status.textContent) {
          status.textContent = " file exceeds file size limit ";
        }
      }
    }
    </script>