Alexeytur
@Alexeytur

Как скачать xls файл через jquery в правильной кодировке?

Добрый день.

На сервере в событии Page_Load генерируется файл:
HttpResponse response = HttpContext.Current.Response;
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "Отчет_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 = "Отчет_133_"+date+".xls";
                    document.body.appendChild(a);
                    a.click();
                }
            });


Пробовал менять ContentType на application/octet-stream, не помогает.
  • Вопрос задан
  • 2369 просмотров
Решения вопроса 1
Alexeytur
@Alexeytur Автор вопроса
Решил через использование 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 = "Отчет_133_" + date + ".xls";
        document.body.appendChild(a);
        a.click();
        HideProgress();
};
ShowProgress();
xhr.send();
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
Stalker_RED
@Stalker_RED
Зачем это шаманство? Сделайте location.replace(url_to_file)

https://codepen.io/stalker-red/pen/gdwPRY?editors=1010
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы