[ASP.net] 按下Button,跳出視窗讓Client端儲存檔案
一般要做另開視窗的下載檔案大概都用以下寫法
<a href=”檔案Url” target=”_blank”>下載</a>
但偏偏就是有客戶堅持一定要按下按鈕post後
才出現一個小視窗讓使用者去儲存檔案,這……很無言的需求= =”
	
奉上程式碼:
protected void ButtonDownloadFile(string fileUrlPath)
    {
        //用戶端的物件
        System.Net.WebClient wc = new System.Net.WebClient();
        byte[] file = null;
        try
        {
            //用戶端下載檔案到byte陣列
            file = wc.DownloadData(fileUrlPath);
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write("ASP.net禁止下載此敏感檔案(通常為:.cs、.vb、微軟資料庫mdb、mdf和config組態檔等)。<br/>檔案路徑:" + fileUrlPath + "<br/>錯誤訊息:" + ex.ToString());
            return;
        }
        HttpContext.Current.Response.Clear();
        string fileName = System.IO.Path.GetFileName(fileUrlPath);
        //跳出視窗,讓用戶端選擇要儲存的地方                         //使用Server.UrlEncode()編碼中文字才不會下載時,檔名為亂碼
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + HttpContext.Current.Server.UrlEncode(fileName));
        //設定MIME類型為二進位檔案
        HttpContext.Current.Response.ContentType = "application/octet-stream";
        try
        {
            //檔案有各式各樣,所以用BinaryWrite
            HttpContext.Current.Response.BinaryWrite(file);
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write("檔案輸出有誤,您可以在瀏覽器的URL網址貼上以下路徑嘗試看看。<br/>檔案路徑:" + fileUrlPath + "<br/>錯誤訊息:" + ex.ToString());
            return;
        }
        //這是專門寫文字的
        //HttpContext.Current.Response.Write();
        HttpContext.Current.Response.End();
    }
2012.3.15 追記:以上是Server端做法,如果用Ajax下載檔案的話,可參考Microsoft AjaxFileDownload