首页 > 解决方案 > 从 Ajax 调用控制器操作时无法下载生成的 PDF

问题描述

我从控制器返回 FilestreamResult 我尝试了 jquery 和 ajax 两种方式,但无法成功从控制器下载 pdf/xlsx 文件。

控制器:

    var filestream = new FileStream(pdfoutputpath + ".pdf", FileMode.Open);
                return new FileStreamResult(filestream, "application/pdf");

使用jquery查看代码:

function downloadpdffile(id) {
                $(".popup-overlay, .popup-content").removeClass("active");
                var url = "/WorkInstructions/WorkinstructionDownload";
                $.get(url, { id: id, fileformat: 2 }, function () {

                });
            }

使用阿贾克斯:

 function downloadpdffile(id) {
                $(".popup-overlay, .popup-content").removeClass("active");
                $.ajax({
                    url: "/WorkInstructions/WorkinstructionDownload",
                    cache: false,
                    type: "GET",
                    data: { id: id, fileformat: 2 },
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function () {

                    }

                });

标签: jqueryasp.netajaxasp.net-mvc-4asp.net-core

解决方案


尝试将其放入您success的 ajax 调用函数中:

success: function(){
    window.location = '@Url.Action("WorkinstructionDownload", "WorkInstructions", new { id = id, fileformat = 2})';
}

虽然我不认为 ajax 在这里提供任何价值,除非我遗漏了什么。您可以轻松地获取success我在上面发布的那个函数的内容,并将其完全放在 ajax 调用之外(并删除 ajax 调用)。或者您可以简单地执行以下操作并完全删除脚本:

<a href="@Url.Action("WorkinstructionDownload", "WorkInstructions", new { id = id, fileformat = 2 })">Download Form</a>


推荐阅读