Получение файла xls через jQuery AJAX breaks file - PullRequest
0 голосов
/ 29 августа 2018

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 голосов
/ 29 августа 2018

Решено с помощью 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();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...