处理ASP.NET MVC FileResult返回

时间:2014-07-03 07:35:34

标签: c# javascript asp.net-mvc asp.net-mvc-3 file

在我的控制器中,我有一个ActionResult,它返回一个文件。

[HttpPost]
public ActionResult ExportCSV(ReportResultViewModel model)   
{     
    var content = "hello,world";
    return File(Encoding.UTF8.GetBytes(content),"text/csv","export.csv");
}

在我看来,当我发布到这个ActionResult时,我会显示一个模态“请等待”。

<!--modal-->
<div class="modal fade" id="pleaseWaitDialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" style="background: #EBF3EB;">
            <div class="modal-header">
                <h1>Please wait...</h1>
            </div>
            <div class="modal-body">
                <div id="loader"></div>
            </div>
       </div>
    </div>
</div>
@using (Html.BeginForm("ExportCSV", "Reporting", FormMethod.Post, new { name = "back", id = "back", style = "width:100%" }))
{
     @Html.HiddenFor(m => m.A)
     @Html.HiddenFor(m => m.LOT)
     @Html.HiddenFor(m => m.OF)
     @Html.HiddenFor(m => m.THINGS)

     <input type="submit" data-toggle="modal" data-target="#pleaseWaitDialog" value="Export CSV" style="width: 100%; background: #fff" class="btn btn-default"  />
}

我希望在文件最终返回页面时隐藏它。

当文件到达时有没有办法检测客户端(可能是JavaScript),所以我可以隐藏模态?

2 个答案:

答案 0 :(得分:1)

我认为你所追求的是你的视图中的jQuery文件下载http://jqueryfiledownload.apphb.com/添加对jquery ui库和文件下载库的引用,然后添加脚本标记。

<script type="text/javascript">

$(function () {
    var $pleaseWaitDialog= $("#pleaseWaitDialog"); 

    $(document).on("submit", "#back", function (e) {

        $pleaseWaitDialog.dialog({ modal: true });

        $.fileDownload($(this).prop('action'), {
            httpMethod: 'POST',
            data: $(this).serialize,
            successCallback: function (url) {
                $pleaseWaitDialog.dialog('close');
            },
            failCallback: function (responseHtml, url) {
                $pleaseWaitDialog.dialog('close');
            }
        });
        e.preventDefault; //otherwise normal form submit will occur 
    });
});
</script>

这样做的是当单击#ExportCSV表单的提交按钮时,它将显示#pleaseWaitDialog标记的模式对话框。然后使用fileDownload插件,它会将一个帖子发送到表单的操作URL。提交的数据来自$(this).serialize调用。成功下载文件或调用失败后,只需关闭对话框。

答案 1 :(得分:0)

如果要捕获返回事件,则必须通过AJAX自行提交原始请求。这意味着JavaScript必须最终负责下载文件,而不是通过Content-Disposition: attachment header下载浏览器。

在您的控制器中,您可以convert the file into a Base64String而不是返回FileActionResult,而是这样返回:

Byte[] bytes = File.ReadAllBytes("path");

if (Request.IsAjaxRequest())
{
    var file64 = Convert.ToBase64String(bytes);
    return Json( new {File = file64, MimeType = mimeType, FileName = fileName});
}
else
{
    // return file - should just auto download
    return File(bytes, mimeType, fileName);
}

然后在您的AJAX处理程序中,您可以use HTML5/Javascript to generate and save a file使用base64 encoding,如下所示:

$(":submit").on("click", function(e) {
    e.preventDefault();
    var $form = $(this).closest('form');

    // disable buttons
    var $btns = $(":submit").addClass("disabled");

    $.ajax({
        type: $form.attr("method"),
        url: $form.attr("action"),
        data: $form.serializeArray(),
        success: function (data) {

            var pom = document.createElement('a');
            pom.setAttribute('href', 'data:' + data.MimeType + ';base64,' + data.File);
            pom.setAttribute('download', data.FileName);

            if (document.createEvent) {
                var event = document.createEvent('MouseEvents');
                event.initEvent('click', true, true);
                pom.dispatchEvent(event);
            }
            else {
                pom.click();
            }

            // reset buttons
            $btns.removeClass("disabled");
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(jqXHR);
        }
    });
});

IE / Edge支持

对于IE /Edge,您需要使用window.navigator.msSaveBlob。如果您要发回base64字符串,则还需要Creating a Blob from a base64 string in JavaScript

进一步阅读

相关问题