jQuery使用AJAX请求加载二进制数据时存在一些问题,因为它尚未实现某些HTML5 XHRv2功能
鉴于此,您拥有以下两种解决方案之一:
与本地htmlHTTPRequest一起使用,这是执行所需操作的代码
var req = new XMLHttpRequest();
req.open("GET", "/file.pdf", true);
req.responseType = "blob";
req.onload = function (event) {
var blob = req.response;
console.log(blob.size);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Dossier_" + new Date() + ".pdf";
link.click();
};
req.send();
该插件可以在此处找到,并且可以用于JQuery中缺少的XHRV2功能,这是如何使用它的示例代码
$.ajax({
dataType: 'native',
url: "/file.pdf",
xhrFields: {
responseType: 'blob'
},
success: function(blob){
console.log(blob.size);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Dossier_" + new Date() + ".pdf";
link.click();
}
});