Download file from ajax and ActionResult

后端 未结 2 1344
既然无缘
既然无缘 2021-01-18 16:47

I want to download files on browser with ajax and ActionResult. The file is downloaded and returned from my ActionResult.

I see the Http query is ok and see the data

2条回答
  •  佛祖请我去吃肉
    2021-01-18 17:02

    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.

提交回复
热议问题