js 上传单个文件(任意大小)

var xml_http,ado_stream;
var SendBlockCount,SendCount;
var lastSendTime,maxFileLimit;
var breaked = false;
var _filename ;
var blockSize = 1024 * 128;
var isUploaded = false;

maxFileLimit = 1024 * 1024 * 50;     //上传文件的大小


///处理文件开始上传
function BeginSend()
{
    try
    {
        if(document.getElementById("UpFileControl") && document.getElementById("UpFileControl").value.length > 0)
        {
            document.getElementById("speed").innerHTML = "0 KB/Sec";              //进度条
            document.getElementById("perent").innerHTML = "0%";
            document.getElementById("perentBar").style.width = "0%";
            document.getElementById("bar").style.display = "block";
            //document.getElementById("control").style.display = "block";
            document.getElementById("divImportData").style.display = "block";
            _filename= document.getElementById("UpFileControl").value;
            document.getElementById("filename").innerHTML = "正在上传文件:"+_filename.substring(_filename.   lastIndexOf("//") + 1,_filename.length);
         
            SendFile();
        }
        else if(document.getElementById("UpFileControl").value =="")
        { 
            alert("请先选择要上传的文件");
            window.parent.AllowFunc();
            document.getElementById("btnReset").disabled = false;
            document.getElementById("btnUpload").disabled = false;
            document.getElementById("UpFileControl").disabled = false;
            Initialize();
            return false;
        }
        else
        {
            return false;
        }
    }
    catch(ex)
    {
        alert("上传文件过程中出错,原因:"+ ex.description);
      //  window.parent.AllowFunc();
        document.getElementById("btnReset").disabled = false;
        document.getElementById("btnUpload").disabled = false;
        document.getElementById("UpFileControl").disabled = false; 
        Initialize();  
        return false;
    }
}

///开始上传文件
function SendFile()
{
    breaked = false;
    try
    {
        ado_stream = new ActiveXObject("ADODB.Stream");
        ado_stream.Type = 1;
        ado_stream.Open();
    }
    catch(ex)
    {
        window.parent.AllowFunc();
        document.getElementById("btnReset").disabled = false;
        document.getElementById("btnUpload").disabled = false;
        document.getElementById("UpFileControl").disabled = false;
        Initialize();
        throw new Error("创建数据流对象失败,原因:"+ex.description);
    }

    try
    {
        ado_stream.LoadFromFile(document.getElementById("UpFileControl").value);
    }
    catch(ex)
    {
        OverSend();       
        window.parent.AllowFunc();
        document.getElementById("btnReset").disabled = false;
        document.getElementById("btnUpload").disabled = false;
        document.getElementById("UpFileControl").disabled = false;
        Initialize();
        throw new Error("无法打开文件 "+document.getElementById("UpFileControl").value+",传输将终止,原因"+ex.description);  
      
        return;
    }

    ado_stream.position = 0;
    if(ado_stream.size == 0)
    {
        OverSend();
        window.parent.AllowFunc();
        document.getElementById("btnReset").disabled = false;
        document.getElementById("btnUpload").disabled = false;
        document.getElementById("UpFileControl").disabled = false;
        Initialize();
        throw new Error("选择的文件为大小为0的空文件,传输将终止");        
        return;
    }

    if(ado_stream.size > maxFileLimit)
    {
        OverSend();
        window.parent.AllowFunc();
        document.getElementById("btnReset").disabled = false;
        document.getElementById("btnUpload").disabled = false;
        document.getElementById("UpFileControl").disabled = false;
        Initialize();
        throw new Error("您选择上传的文件已超过服务器允许上传文件的最大值");      
        return;
    }

    SendCount = Math.ceil(ado_stream.size / blockSize);
    var UpFile = document.getElementById("UpFileControl").value;

    SendBlockCount = 0;
    lastSendTime = new Date();


    xml_http = CreateXmlHttpObj();

    if(xml_http == null)
    {
        OverSend();
        window.parent.AllowFunc(); 
        document.getElementById("btnReset").disabled = false;
        document.getElementById("btnUpload").disabled = false;
        document.getElementById("UpFileControl").disabled = false;
        Initialize();
        throw new Error("创建XmlHttp对象失败,请先下载安装MsXMl组件");
         
        return;   
    }
    try
    {
        SendData();
    }
    catch(ex)
    {
        OverSend();
        window.parent.AllowFunc();
        document.getElementById("btnReset").disabled = false;
        document.getElementById("btnUpload").disabled = false;
        document.getElementById("UpFileControl").disabled = false;
        Initialize();
        throw new Error(ex.description);      
        return;
    }
}

///异步发送文件上传请求到后台程序
function SendData()
{
    if(!breaked)
    {
        xml_http.open("POST","../upload.aspx?ps="+SendBlockCount + "&userName=" + param+"&fileType=" + extendName,true);//添加一个文件类型//不能含有中文//接收上传的页面
        xml_http.onreadystatechange = ShowPerent;
        xml_http.send(ado_stream.Read(blockSize));
    }
}

///显示上传进度
function ShowPerent()
{
    if(xml_http.readystate == 4 && xml_http.status == 200)
    {
        if(xml_http.responseText!="true")
        {
            alert(xml_http.responseText);
            return;
        }
        SendBlockCount++;
        var now = new Date();
        var perentStat = Math.floor(SendBlockCount/SendCount * 100);
        perentStat += "%"

        var sendSpeed = blockSize * SendBlockCount / (now.getTime() - lastSendTime.getTime()) * 1000;

        if(sendSpeed != "Infinity")
        {
            if(sendSpeed < 1000)
            {
                sendSpeed = Math.floor(sendSpeed) + " ";
            }
            else
            {
                sendSpeed = Math.floor(sendSpeed/1024) + " K";
            }
        }
        else
        {
            sendSpeed = "0 ";
        }
        document.getElementById("speed").innerHTML = sendSpeed + "B/Sec";
        document.getElementById("perent").innerHTML = perentStat;
        document.getElementById("perentBar").style.width = perentStat;

        if(SendBlockCount < SendCount)
        {
            SendData();
        }
        else
        {
            OverSend();
            document.getElementById("filename").innerHTML = "上传文件:"+_filename.substring(_filename.lastIndexOf("//") + 1,_filename.length)+"成功"; 
            window.setTimeout("ImportSudentInfo()",10);
        }
    }
}

///取消正在上传的文件
function CancelSend()
{
    if(typeof(xml_http) !='undefined' && xml_http != null)
    {
        breaked = true;
        xml_http.abort();
        DeleteSingleFile();
        OverSend();
    }
}

///结束文件上传
function OverSend()
{
    document.getElementById("bar").style.display = "block";
    document.getElementById("divImportData").style.display = "block";
    var oTextRange = document.body.createTextRange();
    oTextRange.moveToElementText( document.getElementById("UpFileControl") ) ;
    oTextRange.execCommand( 'Cut' ) ;
    oTextRange.execCommand( 'Paste' ) ;
    if(typeof(ado_stream)!="undefined")
    {
        ado_stream.Close();
    }
    breaked = false;
}

///删除指定文件
function DeleteSingleFile()
{
    var xml_http2 = CreateXmlHttpObj();
    if(xml_http2 == null)
    {
        throw new Error("创建XmlHttp对象失败,请先下载安装MsXMl组件");
        return;
    }
    xml_http2.open("POST","../upload.aspx?ps=-1",true);
    xml_http2.setRequestHeader("content-type","application/x-www-form-urlencoded");
    xml_http2.setRequestHeader("Content-Length",param.length);
    xml_http2.send(null);
}

///创建XMLhttp对象
function CreateXmlHttpObj()
{  
try
{ return new ActiveXObject('MSXML2.XMLHTTP.4.0');}
catch(e)
{
  try
  {return new ActiveXObject('MSXML2.XMLHTTP.3.0');}
  catch(e)
  {
     try{return new ActiveXObject('MSXML2.XMLHTTP.2.6');}
     catch(e)
     {
       try{return new ActiveXObject('MSXML2.XMLHTTP');}
       catch(e)
       {
          try{return new ActiveXObject('Microsoft.XMLHTTP');}
          catch(e)
          {
             try{return new XMLHttpRequest();}
             catch(e)
             {
               return null;
              }
           }
        }       
      }
   }
 }

 

 

upload.aspx接收页面后台代码:

protected string username;
    protected void Page_Load(object sender, EventArgs e)
    {
        ///文件模块编号
        string partid = Request.QueryString["ps"];
        this.username = Request.QueryString["userName"];
        string  fileType= Request.QueryString["fileType"];
        if (partid == "" || partid == null || username == "" || username == null)
        {
            Response.Write("系统非法访问!");
            return;
        }

       string filename = username + "考场编排" + fileType;
       string strReturn="true";

       try
       {
           ///获得文件上传目录
           string upPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Uploads");
           if (!upPath.EndsWith("//") && !upPath.EndsWith("/"))
           {
               upPath += "//";
           }
           if (!Directory.Exists(upPath))
           {
               Directory.CreateDirectory(upPath);
           }
           string strDir = upPath;
           ///执行文件删除
           if (partid == "-1")
           {
               //filename = Request.Form["fns"].ToString();
               if (System.IO.File.Exists(strDir + filename))
               {
                   System.IO.File.Delete(strDir + filename);
               }
               return;
           }

           ///执行文件上传操作
           if (partid == "0")
           {
               if (!System.IO.Directory.Exists(strDir))
               {
                   System.IO.Directory.CreateDirectory(strDir);
               }
               if (System.IO.File.Exists(strDir + filename))
               {
                   System.IO.File.Delete(strDir + filename);
               }
           }
           byte[] buffer = Request.BinaryRead(Convert.ToInt32(Request.ContentLength));
           System.IO.FileStream FS = new System.IO.FileStream(strDir + filename, System.IO.FileMode.Append);
           FS.Write(buffer, 0, buffer.Length);
           FS.Close();
           strReturn = "true";

       }
       catch (Exception ex)
       {
           strReturn = "上传文件出错: " + ex.Message;

       }
       finally
       {
           Response.Clear();
           Response.Write(strReturn);
           Response.End();
       }
    
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值