如何在服务器响应下载文件之前制作 jQuery 加载程序

How to make jQuery loader before server responding for download a file

我是法国人,抱歉我的英语不好。

我有一个很慢的 ASP.NET 方法来为我生成一个文件 :

public ActionResult Method([Bind(Prefix = "Id")] Guid id)
{
    //Long work
    return File(data, "application/pdf", doc.Name + ".pdf");
}

在我的 cshtml 文件中有一个按钮(我使用 Razor):

<a title="Télécharger" onclick="DownloadFile('@entity.Id')"/>

和脚本方法:

<script>
    function DownloadFile(id) {
        var url = '@Url.Action("Method", "TheController", new { id = "Id" })'.replace('Id', id);
        $("#divLoading").show();
        $.post(url, null,
        function (data) {
            $("#divLoading").hide();
        });
    }
</script>

div加载:

<div id="divLoading" style="margin: 0px; padding: 0px; position: fixed; right: 0px;
    top: 0px; width: 100%; height: 100%; background-color: #666666; z-index: 30001;
    opacity: .8; filter: alpha(opacity=70);display:none" >
    <p style="position: absolute; top: 30%; left: 45%; color: White;">
        Génération du document...<img src="../../Content/img/ajax-loader.gif">
    </p>
</div>

调用了 C# 方法,divLoading 出现并消失,但导航器未下载文件。

如果我写: 这是工作。 但是装载机不存在。而我想要。

我的问题不是下载文件时如何制作加载器,而是只在下载开始前显示加载器。

谢谢。

您不能直接这样做,因为响应不会发送到浏览器。

作为替代方案,您可以执行 2 个这样的请求:

public ActionResult Method([Bind(Prefix = "Id")] Guid id)
{
    //Long work

    string newGuid = Guid.NewGuid().ToString();
    TempData[newGuid] = data;

    return Content(newGuid);
}

public ActionResult Download(string guid)
{
    byte[] data = (byte[])TempData[guid];

    return File(data, "application/pdf", "teste.pdf");
}

和脚本方法:

function DownloadFile(id) {
    var url = '@Url.Action("Method")';
    $("#divLoading").show();
    $.get(url, 
                function (data, textStatus, jqXHR)
                {
                    $("#divLoading").hide();
                    window.location.href = '@Url.Action("Download")' 
                                            + '?guid=' + data;
                }
           );
}