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(); } }
,如需转载请自行联系原作者