日期:2014-05-17 浏览次数:20416 次
protected void Button1_Click(object sender, EventArgs e)
{
//打开要下载的文件,并把该文件存放在FileStream中
System.IO.FileStream Reader = System.IO.File.OpenRead(Server.MapPath("~/PeaceScore_End.xls"));
//文件传送的剩余字节数:初始值为文件的总大小
long Length = Reader.Length;
Response.Buffer = false;
//Response.AddHeader("Connection", "Keep-Alive");
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + "PeaceScore_End.xls");
Response.AddHeader("Content-Length", Length.ToString());
byte[] Buffer = new Byte[10000]; //存放欲发送数据的缓冲区
int ByteToRead; //每次实际读取的字节数
while (Length > 0)
{
//剩余字节数不为零,继续传送
if (Response.IsClientConnected)
{
//客户端浏览器还打开着,继续传送
ByteToRead = Reader.Read(Buffer, 0, 10000); //往缓冲区读入数据
Response.OutputStream.Write(Buffer, 0, ByteToRead); //把缓冲区的数据写入客户端浏览器
Response.Flush(); //立即写入客户端
Length -= ByteToRead; //剩余字节数减少
}
else
{
//客户端浏览器已经断开,阻止继续循环