[ASP.NET] C# 點擊按鈕來下載檔案 - download file

  • 17989
  • 0

摘要:[ASP.NET] C# 點擊按鈕來下載檔案 - download file

 

 這又是一個自己覺得很簡單的功能,但卻瞬間不知該如何下手的問題(囧ing) "檔案下載" 不就用最最基本的 HTML 都能做到的事嗎?

問題發生的情況:前端使用者輸入資訊,系統產出 QR Code 圖檔,然後以 Image元件 顯示在網頁上,然後要做個按鈕讓使用者可以下載圖檔!

謎之音:就是不要讓使用者還得用右鍵然後另存圖片......XD

底下列出三種可能的方案

  1. 以 System.Web.HttpContext.Current.Response.WriteFile 將檔案輸出
  2. 以 System.Net.WebClient.DownloadData  將檔案輸出
  3. 以 AJAX 作檔案下載  <-- 這個就沒附例子了,請直接參考 http://archive.msdn.microsoft.com/AjaxFileDownload/Release/ProjectReleases.aspx?ReleaseId=3540

----------------------

以 System.Web.HttpContext.Current.Response.WriteFile 將檔案輸出

呼叫方式 xDownload(路徑+檔名 , 另存新檔的預設名稱);

string docupath = Request.PhysicalApplicationPath; //抓取專案所在之路徑
if (!xDownload(docupath + "uploads\\qrcode.png", "qrcode-new.png"))
   lbl_hint.Text = "檔案下載失敗";
 

 

public bool xDownload(string xFile, string out_file) 

//xFile 路徑+檔案, 設定另存的檔名
{
    if (File.Exists(xFile))
    {
        try
        {
            FileInfo xpath_file = new FileInfo(xFile);  //要 using System.IO;
            // 將傳入的檔名以 FileInfo 來進行解析(只以字串無法做)
            System.Web.HttpContext.Current.Response.Clear(); //清除buffer
            System.Web.HttpContext.Current.Response.ClearHeaders(); //清除buffer 表頭
            System.Web.HttpContext.Current.Response.Buffer = false;
            System.Web.HttpContext.Current.Response.ContentType ="application/octet-stream";
            // 檔案類型還有下列幾種"application/pdf"、"application/vnd.ms-excel"、"text/xml"、"text/HTML"、"image/JPEG"、"image/GIF"
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(out_file, System.Text.Encoding.UTF8));
            // 考慮 utf-8 檔名問題,以 out_file 設定另存的檔名
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", xpath_file.Length.ToString()); //表頭加入檔案大小
            System.Web.HttpContext.Current.Response.WriteFile(xpath_file.FullName);

            // 將檔案輸出
            System.Web.HttpContext.Current.Response.Flush();
            // 強制 Flush buffer 內容
            System.Web.HttpContext.Current.Response.End();
            return true;

        }
        catch (Exception)
        {    return false;      }

    }
    else
        return false;
} // EOS xDownload(string xFile, string out_file)

 

----------------------

以 System.Net.WebClient.DownloadData  將檔案輸出

System.Net.WebClient wc = new System.Net.WebClient(); //呼叫 webclient 方式做檔案下載

byte[] xfile = null;
string docupath = Request.PhysicalApplicationPath;
xfile = wc.DownloadData(docupath + "uploads\\qrcode.png");
string xfileName = System.IO.Path.GetFileName(docupath +"uploads\\qrcode.png");
HttpContext.Current.Response.AddHeader("content-disposition","attachment;filename=" +HttpContext.Current.Server.UrlEncode(xfileName));
HttpContext.Current.Response.ContentType = "application/octet-stream"; //二進位方式
HttpContext.Current.Response.BinaryWrite(xfile); //內容轉出作檔案下載
HttpContext.Current.Response.End();

 --------------------

底下這個 QR code 是以「MessagingToolkit.QRCode.Codec」DLL 所產出,晚點在另篇寫 QR code 的產出程式片段

Reference:

  • http://www.dotblogs.com.tw/shadow/archive/2011/03/02/21633.aspx
  • http://fecbob.pixnet.net/blog/post/38087639-c%23-%E5%88%AA%E9%99%A4%E6%AA%94%E6%A1%88--%E4%BF%9D%E5%AD%98%E6%AA%94%E6%A1%88--%E4%B8%8B%E8%BC%89%E6%AA%94%E6%A1%88- 
  • http://archive.msdn.microsoft.com/AjaxFileDownload/Release/ProjectReleases.aspx?ReleaseId=3540