文章出處
文章列表
一般來說我們可以用HTTPHandler來處理一些簡單的邏輯,比如驗證碼、下載文件等。
以下載word文檔為例講解一下如何在HHTPHandler中下載文件,不限于word文檔,如果下載其他文件,需要注意的是要將“
context.Response.ContentType = "application/msword";
”設置為其他相應格式或通用格式“application/octet-stream”,來看代碼1 //文件名 2 const string fileName = "申請表.doc"; 3 //獲取文件路徑 4 string path = context.Server.MapPath("./App_Data/") + fileName; 5 //定義輸出MIME類型 6 context.Response.ContentType = "application/msword"; 7 //以文件流方式下載文件 8 using (FileStream fs = new FileStream(path, FileMode.Open)) 9 { 10 //建立一個byte[]字節數組,長度為要下載文件的大小 11 byte[] bytes = new byte[(int)fs.Length]; 12 //將文件流讀取到byte[]字節數組中 13 fs.Read(bytes, 0, bytes.Length); 14 //通知瀏覽器下載文件而不是打開 15 context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); 16 //將byte[]字節數組寫向瀏覽器 17 context.Response.BinaryWrite(bytes); 18 }
文章列表
全站熱搜