处理filesize AjaxControlToolkit AjaxUpload

时间:2013-07-27 04:57:58

标签: c# javascript asp.net ajax web-config

我想打印错误信息,但我无法提供帮助

这是我在网上某处找到的javascrpit

<script type="text/javascript">
     function AjaxUpload1_OnUploadComplete(sender, e) {
         var size = e.get_fileSize();
         if (size > 289496) {
             var err = new Error();
             err.name = 'My API Input Error';
             err.message = 'Filesize Error';
             throw (err);
         }
         else {
             var div = document.getElementById("status");
             div.innerHTML += "<p>uploaded: " + e.get_fileName() + "</p>";
         }
     }
    </script>

的Ajax

<ajaxToolkit:AjaxFileUpload
    id="AjaxUpload1"
    OnUploadComplete="AjaxUpload1_OnUploadComplete"
    MaximumNumberOfFiles="5"
    AllowedFileTypes="jpg,jpeg,gif,png"
    ThrobberID="MyThrobber"
    runat="server" />

<asp:Image
       id="MyThrobber"
       ImageUrl="/images/indicator.gif"
       Style="display:none"
       runat="server" />

代码隐藏

protected void AjaxUpload1_OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string filePath = "~/images/ajax/" + e.FileName;
        AjaxUpload1.SaveAs(Server.MapPath(filePath));
    }

webconfig

<system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <handlers>
      <add name="AjaxFileUploadHandler" verb="*" path="AjaxFileUploadHandler.axd" type="AjaxControlToolkit.AjaxFileUploadHandler, AjaxControlToolkit"/>
    </handlers>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="289496"/>
      </requestFiltering>
    </security>
  </system.webServer>

上传工作和文件大小没问题,但我想在用户选择大于限制的文件时打印错误。

1 个答案:

答案 0 :(得分:0)

首先,要记住的是,如果您选择上传大于'maxAllowedContentLength'的文件,它将破坏应用程序导致错误,无法完全记住错误代码。

第二,为什么不放弃javascript函数的思想(在上传完成时)并检查代码隐藏OnUploadComplete中的大小,如果不允许,则将标签文本值设置为“不正确的大小”字符串。

你会有这样的东西

在aspx中

<asp:Label runat="server" ID="status" >

和代码隐藏

        protected void AjaxUpload1_OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
               {
                 if(e.FileSize > 289496){ //or something like that    
                 status.Text = "Incorrect size";
                                        }
    else{
                 string filePath = "~/images/ajax/" + e.FileName;
                 AjaxUpload1.SaveAs(Server.MapPath(filePath));
        }
              }