using System; using System.Web; using System.IO; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } //TransmitFile實μ現?下?載? protected void Button1_Click(object sender, EventArgs e) { Response.ContentType = "application/x-zip-compressed"; Response.AddHeader("Content-Disposition", "attachment;filename=z.zip"); string filename = Server.MapPath("DownLoad/z.zip"); Response.TransmitFile(filename); } //WriteFile實μ現?下?載? protected void Button2_Click(object sender, EventArgs e) { string fileName = "asd.txt";//客í戶§端?保£存?的?文?件t名? string filePath = Server.MapPath("DownLoad/aaa.txt");//路·徑? FileInfo fileInfo = new FileInfo(filePath); Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); Response.AddHeader("Content-Length", fileInfo.Length.ToString()); Response.AddHeader("Content-Transfer-Encoding", "binary"); Response.ContentType = "application/octet-stream"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); Response.WriteFile(fileInfo.FullName); Response.Flush(); Response.End(); } //WriteFile分?塊é下?載? protected void Button3_Click(object sender, EventArgs e) { string fileName = "aaa.txt";//客í戶§端?保£存?的?文?件t名? string filePath = Server.MapPath("DownLoad/aaa.txt");//路·徑? var fileInfo = new FileInfo(filePath); if (fileInfo.Exists == true) { const long chunkSize = 102400;//100K 每?次?讀á取?文?件t,?只?讀á取?100K,?這a樣ù可é以?緩o解a服t務?器÷的?壓1力| byte[] buffer = new byte[chunkSize]; Response.Clear(); FileStream iStream = File.OpenRead(filePath); long dataLengthToRead = iStream.Length;//獲?取?下?載?的?文?件t總ü大ó小? Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName)); while (dataLengthToRead > 0 && Response.IsClientConnected) { int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(chunkSize));//讀á取?的?大ó小? Response.OutputStream.Write(buffer, 0, lengthRead); Response.Flush(); dataLengthToRead = dataLengthToRead - lengthRead; } Response.Close(); } } //流÷方?式?下?載? protected void Button4_Click(object sender, EventArgs e) { string fileName = "aaa.txt";//客í戶§端?保£存?的?文?件t名? string filePath = Server.MapPath("DownLoad/aaa.txt");//路·徑? //以?字?符?流÷的?形?式?下?載?文?件t FileStream fs = new FileStream(filePath, FileMode.Open); byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); Response.ContentType = "application/octet-stream"; //通¨知a瀏ˉ覽à器÷下?載?文?件t而?不?是?打ò開a Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); } }