[ASP.NET MVC 5] 通過 Ajax 下載檔案與進度條顯示

在 ASP.NET MVC 網站,我們可以在 Controller 使用 FileContentResult 直接將 byte[] 資料以文件形式發送給瀏覽器。如果希望在頁面加上進度條,讓使用者感覺一下後端處理進度,可以使用 Ajax 。

Ajax 可以讓我們知道伺服器處理資料後回傳的各種情況,但無法直接將檔案送給瀏覽器下載。我們可以利用一些小技巧解決這問題,讓網頁呈現進度條,給使用者感覺一下後端處理進度。

View

假設我們有表單如下:

@using (Html.BeginForm("Download", "Home", FormMethod.Post, new { id = "downloadForm" }))
{
    // 表單內容
}

 <!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" onclick="call()">下載檔案</button>

*** 關於進度條的寫法,請參考Bootstrap 簡易動態進度條***

按下[下載檔案]按鈕,呼叫 ajax,如下所示。

function call()
{
    $.ajax({
       type: "POST",
       url: "/Home/Download",
       data: $("#downloadForm").serialize(),
       success: function (data) {
          if (data != "") {
              window.location = '/Home/GetFile';
              $("#barr").css("width", "100%");
          } else {
          }
      }
    });
}

在這裡 $.ajax 的工作是,調用 Controller 的 Download( ),產生檔案回傳。如果確實有檔案回傳,再通過 window.location 調用 Controller 的 GetFile( ),向使用者的瀏覽器回傳之前產生的檔案。

這時我們可以變更進度條的進度為 100% 。使用者就可看到進度條一路跑至終點,檔案也下載了。

我們看一下 Controller

Download( )

public ActionResult Download( )
{
    FileContentResult excel = null;
    // 以下僅是示意
    byte[] data = new byte[255];
    excel = File(data, "application/vnd.ms-excel");
    Session["excelfile"] = excel; // 將檔案儲存在 Session
    return excel;
}

Download( ) 的工作是產生檔案,例如 Excel,然後將這個檔案儲存在 Session,讓我們之後使用。

GetFile( )

public ActionResult GetFile( )
{
    byte[] data = null;
    FileContentResult file = Session["excelfile"] as FileContentResult;
    data = file.FileContents;
    string fName = "ExcelFile.xls";
    Session["excelfile"] = null;
    return File(data, "application/vnd.ms-excel", fName);
}

GetFile( ) 的工作是,從 Session 取出之前產生的檔案,透過 File( ) 建立 FileContentResult 物件,向使用者的瀏覽器發送檔案。

這篇文章只是說明 Ajax 下載檔案與進度條顯示的小技巧,剩餘的看官自己發揮了。

參考

發表留言