在Ajax通话中下载文件

时间:2018-07-19 02:45:23

标签: javascript c# asp.net-mvc datatables export-to-excel

场景:

我有一个数据表,用户对表进行过滤/排序,然后单击导出按钮。由于数据表是基于服务器端处理构建的,因此我不得不单独编写用于导出的逻辑。当我单击导出时,文件未下载。

代码

[HttpPost]
public FileResult ExportExcelGrid(DataTableAjaxPostModel model)
{
    var objFinderModel = _specFinderExportFlow.ConvertToExportable(model);
    string dateTime = DateTime.Now.ToString("ddMMyyyy");
    var fileDownloadName = "Spec_Finder_Results_" + dateTime + ".xlsx";
    return File(objFinderModel, ExcelExportHelper.ExcelContentType,fileDownloadName);
}

Javascript:

$("#lsc-finder-productexport").on("click", function () {
    $.ajax({
        type: "POST",
        url: "@Url.Action("ExportExcelGrid", "SpecFinder")",
        data: findertable.ajax.params(),
        success: function (response, status, request) {
        },
        failure: function (response) {
        },
        error: function (response) {
        }
    });
});

该调用正在执行,返回二进制数据。如何下载为文件?

这就是我要得到的

enter image description here

更新#2:

我已经更改了代码,例如首先将其下载到服务器中的excel文件,并且在ajax成功时,我将调用文件的路径。仍然不起作用。

代码:

$("#lsc-finder-productexport").on("click", function () {
    $.ajax({
        type: "POST",
        url: "@Url.Action("ExportExcelGrid", "SpecFinder")",
        data: findertable.ajax.params(),
        success: function (response, status, request) {
            window.location.href = response;
        },
        failure: function (response) {
        },
        error: function (response) {
        }
    });
});

C#:

[HttpPost]
public string ExportExcelGrid(DataTableAjaxPostModel model)
{
    var objFinderModel = _specFinderExportFlow.ConvertToExportable(model);
    string dateTime = DateTime.Now.ToString("ddMMyyyy");
    var fileDownloadName = Guid.NewGuid().ToString() + "_Spec_Finder_Results_" + dateTime + ".xlsx";
    var webHost = System.Web.HttpContext.Current.Request.Url.Host;
    var webPort = System.Web.HttpContext.Current.Request.Url.Port;
    var webUrl = webHost + ":" + webPort + "/Content/Export/" + fileDownloadName;
    var serverfilename = Server.MapPath("~/Content/Export/") + fileDownloadName;
    System.IO.File.WriteAllBytes(serverfilename, objFinderModel);
    return webUrl;
}

该文件在该“导出”文件夹中生成,但未下载,下载被取消。

enter image description here

1 个答案:

答案 0 :(得分:0)

您需要创建要下载的链接,以便它自动下载,并且您必须提供文件名,希望此链接对您有所帮助

$("#lsc-finder-productexport").on("click", function () {
    $.ajax({
        type: "POST",
        url: "@Url.Action("ExportExcelGrid", "SpecFinder")",
        data: findertable.ajax.params(),
        success: function (response, status, request) {
            var dowloadlink = document.createElement("a");
                    dowloadlink.download = "test";
                    dowloadlink.href = response;
                    dowloadlink.click();
        },
        failure: function (response) {
        },
        error: function (response) {
        }
    });
});