首页 > 解决方案 > 如何使用 jquery ajax 从 .net core 5 下载文件

问题描述

我有来自 .net core 5 WebApi 的文件响应,我需要通过 ajax 调用下载它。

当我直接从浏览器使用链接时,效果很好。但是如果我把它放在一个ajax调用中,下载的文件就会损坏。这是我的代码:

网络接口:

[HttpGet]
[ActionName("Download")]
public IActionResult GetShipmentCostFile([FromQuery] LogisticFilterModel filter)
{
    var data = GetLogisticRecords(LSP, filter, out int _, 0, 0);
    MemoryStream ms = data.ToExcel();
    return File(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"export_{DateTime.Now:yyyyMMdd}.xlsx");
}

JS:

function DownloadExcel() {
let startDate = $("#billOfDateStart").val();
let endDate = $("#billOfDateEnd").val();
console.log(startDate, endDate);

var settings = {
    "url": "https://localhost:51001/api/logisticdata/download?confirmed=false&date_of_billing_start=2021/3/10&date_of_billing_end=2021/4/1",
    "method": "GET",
    "timeout": 0,
    "headers": {
        "Authorization": "Bearer " + currentUser.idToken,
    },
};

$.ajax(settings).done(function (response) {
    console.log(response);
    var blob = new Blob([response], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    })
    var url = window.URL || window.webkitURL;
    link = url.createObjectURL(blob);
    var a = $("<a />");
    a.attr("download", "export.xlsx");
    a.attr("href", link);
    $("body").append(a);
    a[0].click();
    $("body").remove(a);
});

我无法使用直接链接下载,因为我需要在请求中添加身份验证标头。

如果有人可以提供帮助,非常感谢。

标签: javascriptajax.net-core

解决方案


推荐阅读