请朋友们看贴或回贴时稍稍仔细一点用asp.net如何"控制"用户上传过大的文件,注意是限制,而不是突破限制。请不要简单地回贴说限定web.config中的上传值,这个我知道。
问题是,如果你设置为4M,用户上传超过4M的,系统会给用户一个非常不友好的出错界面The page cannot be displayed,
这显然是做程序的大忌。设为2G?拜托网站不是这么玩的。现在想达到一个这样的目标:
1.提前判断用户上传数据大小,超过限定值就中止用户端上传,并向用户返回一个友好的提示(或者跳转到一个指定页面)
  用Request.File.ContentLength来判断是不可取的,因为它是在文件全部上传并缓存到服务器上后才能取得长度值的。
  缺点是过多地占用服务器资源,如果数据超过限定值时还会出现不友好错误界面。很多资料显示通过HttpWorkerRequest
  来在处理上传之前判断表单正文数据长度GetTotalEntityBodyLength,能够做到预先判断,当然是好办法了。
2.当通过GetTotalEntityBodyLength判断将上传的文件超过限定值时,我们应该如何处理呢?简单地说,如何通知客户端浏览器不要上传这个文件或表单,同时向用户返回一个友好的提示(当然能跳转到一个指定页更好)。请高人指点,这一点如何实现

解决方案 »

  1.   

    ///使用說明
    ////直接引用
    //文件大於4M將不能上載
    function CheckFileSize(obj)
    {
    if(obj==null)
    obj=window.event.srcElement;
    var id=obj.id;
        var maxLength=4096000;//4M
        var fso = new ActiveXObject('Scripting.FileSystemObject');
        if(obj.value.trim()=="")
    return;
        if(fso.FileExists(obj.value))
        {
            var file = fso.GetFile(obj.value);
            if(file.Size>maxLength)
            {
                alert('The size of attachment exceed 4Mb.');
                obj.outerHTML=obj.outerHTML;
                document.getElementById(id).attachEvent("onkeydown",function() {CheckKeyDown(document.getElementById(id));});
    document.getElementById(id).attachEvent("onchange",function() {CheckFileSize(document.getElementById(id));});
            }
        }
        else
        {
    alert('File does not exist.');
    obj.outerHTML=obj.outerHTML;
    document.getElementById(id).attachEvent("onkeydown",function() {CheckKeyDown(document.getElementById(id));});
    document.getElementById(id).attachEvent("onchange",function() {CheckFileSize(document.getElementById(id));});
        }
    }//Backspace & Delete鍵有效,並且將FileField內容清空
    function CheckKeyDown(obj)
    {
    if(obj==null)
    obj=window.event.srcElement;
    var id=obj.id;
    if(window.event.keyCode!=8&&window.event.keyCode!=46)
    {
    window.event.returnValue=false;
    }
    else
    {
    window.event.returnValue=false;
    obj.outerHTML=obj.outerHTML;
            document.getElementById(id).attachEvent("onkeydown",function() {CheckKeyDown(document.getElementById(id));});
    document.getElementById(id).attachEvent("onchange",function() {CheckFileSize(document.getElementById(id));});
    }
    }if (document.all)
    {
    window.attachEvent("onload",function(){AddEvent();})
    }
    else
    {
    window.addEventListener("load",function(){AddEvent();},false);
    }function AddEvent()

    var input_file=document.getElementsByTagName("INPUT");
    for (var i=0; i<input_file.length; i++)

    if (input_file[i].type=="file") 
    {
    input_file[i].attachEvent("onkeydown",function() {CheckKeyDown(null);});
    input_file[i].attachEvent("onchange",function() {CheckFileSize(null);});

    }
    }String.prototype.trim= function()  
    {  
    return this.replace(/(^\s*)|(\s*$)/g, "");  
    }
      

  2.   


    没用的.IE6有用,FF及IE7 IE8失效 .