首页 > 解决方案 > 使用 ajax 下载 .net core 生成的 pdf 文件

问题描述

我正在努力使用 ajax 调用下载带有 .net 核心的生成的 pdf。基本上我有一个用户需要选择然后打印 pdf 输出的订单列表。我可以使用带有操作链接的按钮来做到这一点,但我需要以某种方式传入选定的值(选定的复选框),因此我使用 ajax 并传入这些值。

到目前为止,我有这个:

html:

<button id="btnPrintSelectedOrdersDeliveryLabels">Print labels</button>

C#:

return File(Convert.FromBase64String(deliveryAPIprintLabelsResult.Labels), "application/pdf", "delivery_labels.pdf");

javascript:

       $.ajax({
        method: "GET",
        url: '@Url.Action("PrintDeliveryLabelsByOrderId", "Delivery")',
        cache: false,
        data: {
            orderIds: JSON.stringify(orderIds)
        },
        success: function(result) {

            var blob = new Blob([result], { type: 'application/pdf' });
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = 'delivery_labels.pdf';

            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

        },
        error: function() {
            console.log('error!');
        }
    });       
}

我很确定错误在 ajax 成功调用中的某个地方,因为我得到了一个 pdf 但它是空白的。

标签: jquery.netasp.net-core

解决方案


我想到了。Jquery 不支持“blob”,所以最终的解决方案应该使用 XHR。


推荐阅读