ASP.NET 附件彈窗下載


      發的隨筆,不能每個都上首頁,微微蛋疼啊。啊哈。這次再發一個關於附件下載的。

      前段時間做項目,本來附件下載直接一個a標記找到文件就可以了。但是呢,每次打開txt啊,圖片啊。都是直接瀏覽器打開。我們測試都說了,你們那咋搞的,我一點就打開了。想下載也沒辦法(搞了個自定義右鍵菜單),我說那是你系統問題。關我電腦毛事啊。。人說,你看別人的都可以。。。然后我就傷不起了。。就有了這么一小段代碼。

      話說,測試跟開發真是天生冤家啊。好好的代碼,本地一點事沒有,一到測試環境,各種奇葩BUG,每次都先跟他們說,清緩存,清緩存的。。。我恨測試。

      其實很簡單的代碼,就是加一個全局Hanlder。

AttachmentDownloadHanlder
 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Web;
 7 
 8 namespace Wanda.SICI.UI.Web
 9 {
10     public class AttachmentDownloadHanlder : IHttpHandler
11     {
12         public void ProcessRequest(HttpContext context)
13         {
14             string path = context.Request.PhysicalPath;
15 
16             try
17             {
18                 context.Response.Charset = "UTF-8";
19                 context.Response.ContentEncoding = Encoding.UTF8;
20                 context.Response.HeaderEncoding = Encoding.UTF8;
21                 context.Response.AppendHeader("Content-disposition",
22                                               "attachment; filename=" +
23                                               HttpUtility.UrlEncode(Path.GetFileName(path), Encoding.UTF8));
24                 context.Response.WriteFile(path);
25             }
26             catch (Exception ex)
27             {
28                 context.Response.Write("下載文件出錯,原因:" + ex.Message);
29             }
30             finally
31             {
32                 context.Response.End();
33             }
34         }
35 
36         public bool IsReusable { get { return false; } }
37     }
38 }

 

然后再添加一個配置文件,配置文件放到你的附件根目錄就可以了。

 

web.config
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <configuration>
 3   <system.web>
 4     <httpHandlers>
 5       <add verb="*" path="*" type="Wanda.SICI.UI.Web.AttachmentDownloadHanlder"/>
 6     </httpHandlers>
 7   </system.web>
 8   <system.webServer>
 9     <handlers>
10       <add name="AttachmentDownloadHanlder" verb="*" path="*"
11         modules="IsapiModule" 
12         scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll"
13         resourceType="File"
14            />
15     </handlers>
16   </system.webServer>
17 </configuration>

如果報錯的話,就把%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll改成

%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll 就可以了。

最開始的時候,一直500,后來一查,說什么要啟用iis的32位模擬什么的。

這樣每次下載,都會把附件標記,不會使用瀏覽器打開了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM