如何在asp.net中的ajaxtoolkit ajaxfileupload控件中上传多个文件之前检查每个文件的文件大小?

时间:2013-07-25 17:43:44

标签: asp.net ajaxcontroltoolkit

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

文件背后的代码

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

        }
    }

我想在文件上传事件之前检查所有文件大小是否不应超过特定值。

5 个答案:

答案 0 :(得分:3)

尝试这种方式:

服务器端:

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;
    }
}

在客户端:

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

希望这会有所帮助!!

答案 1 :(得分:1)

    <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;" />

答案 2 :(得分:0)

请参阅以下代码:

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;
     }}

答案 3 :(得分:0)

这个想法是防止文件上传到服务器。在建议的解决方案中,当流代码已达到afuUpload_UploadedComplete时,文件已上载到服务器,但尚未记录在您指定的路径中。例如,如果限制为20兆字节且所选文件为22兆字节,则当代码达到afuUpload_UploadedComplete时,已将22兆字节上载到服务器。

所寻求的解决方案是验证在客户端(JavaScript)完成,并阻止代码到达服务器上的CodeBehind

在我的情况下,我尝试OnClientUploadComplete在超出文件大小限制时生成异常,但它不起作用且代码仍然到达CodeBehind。另一个问题是,当异常发生时,JavaScript函数OnClientUploadError不会触发来拦截OnClientUploadComplete函数中生成的异常。

答案 4 :(得分:0)

控制器

  [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" />