How to check file size of each file before uploadi

2020-07-24 05:21发布

问题:

<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.

回答1:

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!!



回答2:

    <script type="text/javascript">
    $(".ajax__fileupload_dropzone").bind("drop", function () {
            checkfilesize();
    });
    $(".ajax__fileupload_queueContainer").bind("click", function () {       
            checkfilesize();
    });  
    $(".ajax__fileupload_uploadbutton").bind("mouseenter", function () {
            checkfilesize();
    });

    function checkfilesize() {
        var total_filesize_num = 0;
        var myElements = $(".filesize");
        if (myElements.length == 0) {
            $(".ajax__fileupload_uploadbutton").css("visibility", "hidden");
            return;
        }
        for (var i = 0; i < myElements.length; i++) {              
            var filesize = myElements.eq(i).html(); //$(".filesize").html();     
            total_filesize_num = total_filesize_num + filesize_tonum(filesize);
        }
        if (total_filesize_num > 5) {
            $(".ajax__fileupload_uploadbutton").css("visibility", "hidden");
            alert('Maximum file size is 5MB only! Please select another one.');
            return;
        } else {
            $(".ajax__fileupload_uploadbutton").css("visibility", "visible");
        }
    }
    function countsumfilesize() {
        var sumfilesize = 0;
        var myElements = $(".filesize");
        for (var i = 0; i < myElements.length; i++) {
            alert(myElements.eq(i).html());
        }
    }
    function filesize_tonum(filesize) {
        var filesize_num = 0;
        if (filesize.indexOf("kb") > 0) {
            var space = filesize.lastIndexOf(" ");
            filesize_num = parseFloat("0." + filesize.substr(0, filesize.length - space + 1));
        }
        else if (filesize.indexOf("MB") > 0) {
            var space = filesize.lastIndexOf(" ");
            filesize_num = parseFloat(filesize.substr(0, filesize.length - space + 1));
        }    
        return filesize_num;
    }

    </script>

<ajaxToolkit:AjaxFileUpload ID="AjaxFileUploadImage" runat="server" OnClientUploadComplete="uploadComplete" MaximumNumberOfFiles="1" AllowedFileTypes="gif,png,jpg,jpeg" onchange="checkfilesize(); return false;" />


回答3:

See the code below:

public void afuUpload_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
    {
     try
     {
       string savePath = MapPath("~/Uploads/" + Path.GetFileName(e.filename));
       if (int.Parse(e.filesize) > 3000000)
       {
          return;
       }
       afuUpload.SaveAs(savePath);
     }
     catch (Exception ex)
     {
        throw ex;
     }}


回答4:

The idea is to prevent the file is uploaded to the server. In the proposed solution, when the flow code has reached afuUpload_UploadedComplete, the file was uploaded to server, but has not yet been recorded in the path you specify. For example, if the limit is 20 megabytes and the selected file is 22 megabytes, when the code reaches afuUpload_UploadedComplete, 22 Megabytes already been uploaded to the server.

The solution sought is that the validation is done on the client side (JavaScript) and that prevents the code arrives to CodeBehind on the server.

In my case, I tried to OnClientUploadComplete generating an exception when the file size limit is exceeded, but it did not work and the code is still reaching the CodeBehind. The other problem is that when the exception occurs, the JavaScript function OnClientUploadError is not firing to intercept the exception generated in OnClientUploadComplete function.



回答5:

Controller

  [HttpPost]
 public ActionResult Create(string Album, Photo photo, IEnumerable<HttpPostedFileBase> files, DateTime? datec, string NewAlbum = null)
  {
  .....

     foreach (var file in files)
            {
                decimal sum = file.ContentLength / 1048;
                if (sum > 4000)
                {
                    errorlist2 += "Sorry " + file.FileName + " has exceeded its file limit off 4 MB  <br/>";


                }

            }

   if (errorlist2 != "")
                {
                    ViewBag.Error = errorlist2;
                    return View(photo);
                }

  // we dont want put the message in the loop it will come out on first max limit , rather find all files in excess, then we can pass the message 
  //also make sure your web config is set  for a limit on max size 

//using the normal html multi uploaded

// <input type="file" name="files" id="files" required multiple="multiple" accept=".jpg, .png, .gif" size="4" />