Get excel file (.xlsx) from server response in ajax
It looks like JQuery have got some problem with dealing with the binary data from the response. I used simply XMLHttpRequest and I add all data to the URL.
var request = new XMLHttpRequest();request.open('POST', url, true);request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');request.responseType = 'blob';request.onload = function(e) { if (this.status === 200) { var blob = this.response; if(window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveBlob(blob, fileName); } else{ var downloadLink = window.document.createElement('a'); var contentTypeHeader = request.getResponseHeader("Content-Type"); downloadLink.href = window.URL.createObjectURL(new Blob([blob], { type: contentTypeHeader })); downloadLink.download = fileName; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); } } }; request.send();
After so many searches for getting an excel file from web API with Unicode content. Finally, this code works for me :
$.ajax({ type: 'GET', cache: false, url: "https://localhost:44320/WeatherForecast", xhrFields: { // make sure the response knows we're expecting a binary type in return. // this is important, without it the excel file is marked corrupted. responseType: 'arraybuffer' } }) .done(function (data, status, xmlHeaderRequest) { var downloadLink = document.createElement('a'); var blob = new Blob([data], { type: xmlHeaderRequest.getResponseHeader('Content-Type') }); var url = window.URL || window.webkitURL; var downloadUrl = url.createObjectURL(blob); var fileName = ''; if (typeof window.navigator.msSaveBlob !== 'undefined') { window.navigator.msSaveBlob(blob, fileName); } else { if (fileName) { if (typeof downloadLink.download === 'undefined') { window.location = downloadUrl; } else { downloadLink.href = downloadUrl; downloadLink.download = fileName; document.body.appendChild(downloadLink); downloadLink.click(); } } else { window.location = downloadUrl; } setTimeout(function () { url.revokeObjectURL(downloadUrl); }, 100); } });
We were having absolutely the same trouble recently. For us it started to work when we add responseType: 'arraybuffer'
to the ajax
parameters. And it's better to use lib https://github.com/eligrey/FileSaver.js/
instead of manual clicking on the link because this tool revokes memory as well.