首先有一個html頁面,頁面有一個鏈接,點擊鏈接彈出文件下載/保存(類似迅雷下載鏈接) <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title> ...
首先有一個html頁面,頁面有一個鏈接,點擊鏈接彈出文件下載/保存(類似迅雷下載鏈接)
![](http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>文件下載</title> <meta charset="utf-8" /> </head> <body> <!--該方式不行,1:如果訪問的是類似文本等瀏覽器可以處理的文件,則是瀏覽器打開顯示的方式,並不是文件下載;2:如果訪問的是App_Data文件夾里的文件,由於.net的機制不允許訪問App_Data文件夾資源,所以會報“請求篩選模塊被配置為拒絕包含 hiddenSegment 節的 URL 中的路徑。”--> <a href="App_Data/readme.txt">下載readme.txt文件</a> <br /> <a href="DownloadFileHandler.ashx">下載readme.txt文件</a> </body> </html>View Code
一般處理程式的代碼如下
![](http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System.IO; using System.Web; namespace Zhong.Web { /// <summary> /// DownloadFileHandler 的摘要說明 /// </summary> public class DownloadFileHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { string filePath = context.Server.MapPath("~/App_Data/readme.txt"); FileStream fs = new FileStream(filePath, FileMode.Open); byte[] bytes = new byte[fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Dispose(); context.Response.ContentType = "application/octet-stream"; context.Response.AddHeader("Content-Disposition", "attachment; filename=readme.txt"); context.Response.BinaryWrite(bytes); context.Response.Flush(); //大文件下載的解決方案 //context.Response.ContentType = "application/x-zip-compressed"; //context.Response.AddHeader("Content-Disposition", "attachment;filename=z.zip"); //string filename = Server.MapPath("~/App_Data/move.zip"); //context.Response.TransmitFile(filename); } public bool IsReusable { get { return false; } } } }View Code
點擊第一個鏈接訪問,顯示如下:
點擊第二個鏈接訪問,下載文件:
由於我之前已經測試過一次,所以這次下載時命名為readme(1).txt