Download file from ajax and ActionResult Download file from ajax and ActionResult ajax ajax

Download file from ajax and ActionResult


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'); }