分块下载文件的思路

  如果多人访问服务器,从服务器中下载文件,服务器将会承受巨大的压力。所以,在编写下载文件代码时要考虑到服务器的承受能力。很多读者都是直接读取整个文件进行下载,显然这种下载方式很不科学。采用分块下载文件,每次从服务器中读取固定大小的文件,会大大的缓解了多人访问时给服务器带来的压力。

1,使用File类的OpenRead方法以文件流的形式打开要下载的文件以便进行读取。

2,使用FileStream类的Length属性获取打开的文件流的长度。

3,使用FileStream类的Read方法开始从文件流中读取固定大小的字节块并存储到byte数组中。

4,使用OutputStrem对象的Write方法将读取的文件写入输出流中。

5,从文件流总长度中减去已读取的长度。

6,继续执行3中的代码读取文件。

    private void DownLoadFile(string path)
    {
        string serverpath = Server.MapPath(path);
        FileInfo fi = new FileInfo(serverpath);
        if (fi.Exists)
        {
            const long size = 2048;//2K
            byte[] buffer = new byte[size];
            Response.Clear();
            FileStream fs = File.OpenRead(serverpath);
            long data = fs.Length;
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Path.GetFileName(serverpath)));
            while (data > 0 && Response.IsClientConnected)
            {
                int readlength = fs.Read(buffer, 0, Convert.ToInt32(size));
                Response.OutputStream.Write(buffer, 0, readlength);
                Response.Flush();
                data = data - readlength;
            }
            Response.Close();
        }
    }
原文地址:https://www.cnblogs.com/chirifengye/p/2833636.html