检测FileStreamResult何时完成

时间:2015-03-19 13:13:07

标签: c# asp.net-mvc

我有一个ASP.NET MVC应用程序。在我看来,我有一个按钮,上面写着"下载"。当用户单击此按钮时,文本将更改为"正在下载..."。我的代码如下所示:

View.cshtml

<button id="myButton" onclick="downloadClick();"><span>Download</span></button>

function downloadClick() {
  $('#myButton').html('<span>Downloading...</span>');
  window.location = '/download/latest';      
}

此代码成功下载文件。位于/download/latest的控制器操作如下所示:

MyController.cs

public class MyController {
  public ActionResult DownloadLatest() {
    var someUrl = "https://my-domain.com/files/latest";
    using (var fileClient = new HttpClient())
    {
      var file = await fileClient.GetStreamAsync(fileUrl);
      Response.ClearContent();
      Response.ClearHeaders();

      Response.AppendHeader("Content-Disposition", "Attachment; Filename=latest.txt");

      return new FileStreamResult(file, "txt");
    }              
  }
}

该文件已成功下载。但是,我无法弄清楚如何将按钮文本恢复为&#34; download&#34;在检索到响应之后。我该怎么做?

谢谢!

1 个答案:

答案 0 :(得分:1)

向执行AJAX调用的按钮添加单击事件。然后你可以在返回时关闭微调器。

$('#adcExportToExcel').click(function () {
          $('#adcExportToExcel').spin('small');
          var data = $("#adcResult").data('gridData');      
          data = JSON.stringify(data);
          var actionUrl = '@Url.Action("GenerateExcelReport", "ADC")';
          var getUrl = '@Url.Action("DownloadExcelReport", "ADC")';

          $.ajax(actionUrl, {
              contentType: 'application/json; charset=utf-8',
             dataType: 'json',
             type: 'POST',
             data: data,
             success: function (d) {
                 if (d.success) {
                     window.location = getUrl + "?fName=" + d.fName;
                 }
             },
             error: function () {

             }
         }).always(function() {
             $('#adcExportToExcel').spin(false);
         });

});

See this blog post