通过jQuery AJAX中断文件获取xls文件

时间:2018-08-28 23:38:28

标签: jquery asp.net ajax

Hellow。

在服务器上,在Page_Load事件中生成一个文件:

HttpResponse response = HttpContext.Current.Response;
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "Report_133_" + ReportDate.ToShortDateString() + ".xls"));
response.Clear();
response.BinaryWrite(ms.GetBuffer());
fs.Close();
ms.Close();
response.End();

如果我通过正常的浏览器转换导航到此页面,则文件将正常下载。但是,如果我通过jQuery AJAX获得它,那么文件将返回损坏的文件。 jQuery代码:

$.ajax({
                type: 'GET',
                url: 'Get133Report.aspx?date=' + date,
                beforeSend: function () {
                    ShowProgress();
                },
                complete: function () {
                    HideProgress();
                },
                //async: true,
                success: function (response) {
                    //console.log(response);
                    var blob = new Blob([response], { type: 'application/vnd.ms-excel' });
                    var downloadUrl = URL.createObjectURL(blob);
                    var a = document.createElement("a");
                    a.href = downloadUrl;
                    a.download = "Report_133_"+date+".xls";
                    document.body.appendChild(a);
                    a.click();
                }
            });

尝试将ContentType更改为application / octet-stream没有帮助。

1 个答案:

答案 0 :(得分:0)

使用XMLHttpRequest解决

var xhr = new XMLHttpRequest();
xhr.open('GET', 'Get133Report.aspx?date=' + date, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
        var blob = new Blob([this.response], { type: 'application/vnd.ms-excel' });
        var downloadUrl = URL.createObjectURL(blob);
        var a = document.createElement("a");
        a.href = downloadUrl;
        a.download = "Report_133_" + date + ".xls";
        document.body.appendChild(a);
        a.click();
        HideProgress();
};
ShowProgress();
xhr.send();