asp.net使用一般處理常式實現檔案下載

來源:互聯網
上載者:User

標籤:href   []   方案   方式   map   txt   ade   pos   content   

首先有一個html頁面,頁面有一個連結,點選連結彈出檔案下載/儲存(類似迅雷下載連結)

<!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

一般處理常式的代碼如下

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

asp.net使用一般處理常式實現檔案下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.