Download file from ajax and ActionResult

本小妞迷上赌 提交于 2019-12-01 22:50:15

AJAX is just a thin client. Nothing happens with the response returned by default. You are responsible to making the download happen. However, doing that requires the File API that's part of HTML5. As a result, this is only possible in modern browsers (IE10+).

Inside your AJAX success method:

var blob = new Blob(data, { type: 'application/pdf' });
var a = document.createElement('a');
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'myfile.pdf';
a.click();
window.URL.revokeObjectURL(url);

EDIT

jQuery doesn't interpret the response type correctly by default. You'll need to modify your $.ajax call slightly:

$.ajax({
    url: '../Shipping/ShippingDownloadDNPriority?SALE_GUID=XXXXXXXXXXXXXX',
    data: { SALE_GUID: DropShipping.GetRowKey(rowIndexSale) },
    async: false,
    // -- ADD THIS --
    xhrFields: {
        responseType: 'blob'
    },
    success: function (data) {
        // code above here, but no longer need to create blob
        var a = document.createElement('a');
        var url = window.URL.createObjectURL(data);
        a.href = url;
        a.download = 'myfile.pdf';
        a.click();
        window.URL.revokeObjectURL(url);
    }
});

You can check out a CodePen here to see it working.

I changed of idea. I simply send my pdf (from my controller) in 64 base and make in the ajax :

success: function (data) {
     window.open("data:application/pdf;base64," + data.data, '_blank'); 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!