zoukankan      html  css  js  c++  java
  • 多线程 断点续传

    Stream iStream = null;
    byte[] buffer = new Byte[10240];// 缓冲区块10K bytes :
    int length;            
    long dataToRead;           
    string filepath = @"E:\software\SQL Server 2000 Personal Edition.ISO";
    string filename = System.IO.Path.GetFileName(filepath);
    try
    {
        // 打开文件
        iStream = new FileStream(filepath, FileMode.Open,FileAccess.Read, FileShare.Read);
        Response.Clear();
        dataToRead = iStream.Length;
        long p = 0;
        if (Request.Headers["Range"] != null)
        {
            Response.StatusCode = 206;
            p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));
        }
        if (p != 0)
        {
            Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long)(dataToRead - 1)).ToString() + "/" + dataToRead.ToString());
        }
        Response.AddHeader("Content-Length", ((long)(dataToRead - p)).ToString());
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(Request.ContentEncoding.GetBytes(filename)));
    
        iStream.Position = p;
        dataToRead = dataToRead - p;              
        while (dataToRead > 0)
        {                  
            if (Response.IsClientConnected)
            {               
                length = iStream.Read(buffer, 0, 10240);                     
                Response.OutputStream.Write(buffer, 0, length);                      
                Response.Flush();
    
                buffer = new Byte[10240];
                dataToRead = dataToRead - length;
            }
            else
            {
                //如果用户断开连接 防止无限循环
                dataToRead = -1;
            }
        }
    }
    catch (Exception ex)
    {             
        Response.Write("Error : " + ex.Message);
    }
    finally
    {
        if (iStream != null)
        {
            iStream.Close();
        }
        Response.End();
    }
    }
  • 相关阅读:
    Mongo简单查询总结
    将对象转换成Dictionary 字典
    C#调用NPOI组件导出Excel表格
    Lambda中的一些方法的总结
    LinQ总结
    简单的爬虫 一
    Python 中的注释规范
    在VM上配置一个能上网的网络设置
    Python 中新式类的内置方法
    Python 中的locals()
  • 原文地址:https://www.cnblogs.com/zengxiangzhan/p/1659983.html
Copyright © 2011-2022 走看看