I use this code to download excel file from server.
$.ajax({ headers: CLIENT.authorize(), url: '/server/url', type: 'POST', contentType: "application/json; charset=utf-8", data: JSON.stringify(jsonData), success: function (data) { alert('Data size: ' + data.length); var blob = new Blob([data], { type: "application/vnd.ms-excel" }); alert('BLOB SIZE: ' + data.length); var URL = window.URL || window.webkitURL; var downloadUrl = URL.createObjectURL(blob); document.location = downloadUrl; }, });
The problem I experience is that even though data and blob sizes are identical, the moment document.location gets assigned I'm prompted to download almoste two times larger excel file. And when I try to open it, excel complains about wrong file format and opened file contains a lot of garbage, even though required text is still there.
Any ideas what is causing this and how to avoid it?
Creating the download link Create an object URL for the blob object. Create an anchor element ( <a></a> ) Set the href attribute of the anchor element to the created object URL. Set the download attribute to the filename of the file to be downloaded.
The Blob Interface and Binary Data. A Blob object refers to a byte sequence, and has a size attribute which is the total number of bytes in the byte sequence, and a type attribute, which is an ASCII-encoded string in lower case representing the media type of the byte sequence.
Downloading Excel File using AJAX in jQueryInside the DownloadFile JavaScript function, the URL of the File is passed as parameter to the jQuery AJAX function. Inside the jQuery AJAX function, using the XmlHttpRequest (XHR) call, the PDF file is downloaded as Byte Array (Binary Data).
So I solved the problem using AJAX 2. It natively supports binary streams. You can't use jQuery for that, unless you base64 encode everything, apparently.
Working code looks like this:
var xhr = new XMLHttpRequest(); xhr.open('POST', '/le/url', true); xhr.responseType = 'blob'; $.each(SERVER.authorization(), function(k, v) { xhr.setRequestHeader(k, v); }); xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8'); xhr.onload = function(e) { preloader.modal('hide'); if (this.status == 200) { 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 = "data.xls"; document.body.appendChild(a); a.click(); } else { alert('Unable to download excel.') } }; xhr.send(JSON.stringify(jsonData));
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With