javascript - Downloading file from ajax result using blob -
i use code download excel file 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 experience though data , blob sizes identical, moment document.location gets assigned i'm prompted download almoste 2 times larger excel file. , when try open it, excel complains wrong file format , opened file contains lot of garbage, though required text still there.
any ideas causing , how avoid it?
so solved problem using ajax 2. natively supports binary streams. can't use jquery that, unless base64 encode everything, apparently.
working code looks 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 = document.createelement("a"); a.href = downloadurl; a.download = "data.xls"; document.body.appendchild(a); a.click(); } else { alert('unable download excel.') } }; xhr.send(json.stringify(jsondata));
hope helps.
Comments
Post a Comment