A
A
Alexeytur2018-08-29 02:11:38
JavaScript
Alexeytur, 2018-08-29 02:11:38

How to download xls file via jquery in correct encoding?

Good afternoon.

On the server, in the Page_Load event, a file is generated:

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();


If you go to this page with a normal browser transition, then the file is downloaded normally. But if you get it via jQuery AJAX, then the file is returned broken.
jquery code:
$.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();
                }
            });


Tried changing ContentType to application/octet-stream, doesn't help.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexeytur, 2018-08-29
@Alexeytur

Solved through using XMLHttpRequest directly

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();

S
Stalker_RED, 2018-08-29
@Stalker_RED

Why is this shamanism? Make location.replace(url_to_file)
https://codepen.io/stalker-red/pen/gdwPRY?editors=1010

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question