我正在尝试编写将blob作为pdf下载到所有浏览器的代码。 我正在使用以下代码。该代码适用于最新的铬和铬,但在旧版本的铬中失败。
var http = new XMLHttpRequest();
if (product && product.toUpperCase() == 'a') {
http.open("POST", someURL, true);
}
else {
http.open("POST", someURL, true);
}
http.setRequestHeader("Content-type", "application/json");
http.responseType = 'arraybuffer';
var blob = window.Blob || window.mozBlob || window.web;
http.onload = function (e) {
var contentType = http.getResponseHeader('Content-Type');
if (e.currentTarget.status == 200) {
console.log(e.currentTarget.response);
try {
blob = new Blob([e.currentTarget.response], { type: 'application/pdf',encoding:'raw' });
}
//backward compatibility
catch (error) {
window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
if (error.name == 'TypeError' && window.BlobBuilder) {
var blobBuilder = new BlobBuilder();
console.log(e.currentTarget.response);
blobBuilder.append(e.currentTarget.response);
blob = blobBuilder.getBlob('application/pdf');
}
}
// window.saveAs(blob,"abcd.pdf");
var downloadUrl = (window.URL ? URL : webkitURL).createObjectURL(blob);
var a = document.createElement("a");
//IE support for blob ,as it gives exception
if (window.navigator.msSaveOrOpenBlob) {
$(a).click(function () {
window.navigator.msSaveOrOpenBlob(blob, title + '.pdf');
});
}
if (('download' in a)) {
// Chromium browser and the chrome version is greater than 20
// Chromium version>20
a.href = decodeURIComponent(downloadUrl);
a.target = '_blank';
a.download = title + '.pdf';
document.body.appendChild(a);
// setTimeout(function () {
// a.click();
// document.body.removeChild(a);
// }, 66);
// a.href = decodeURIComponent(downloadUrl);
// a.target ='_blank';
// a.download = title + '.pdf';
// document.body.appendChild(a);
if("click" in a ){
a.click();
}else if("dispatchEvent" in a){
console.log('in dispatch event ');
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
console.log(evt);
a.dispatchEvent(evt);
}
对于我在下载时测试的特定版本的chrome,支持属性,但不支持click()函数。 我试图使用dispatch事件来触发点击链接,它不闪现任何错误但什么都不做。 我也尝试过使用FileSaver.js,但这对我来说并不适用。
提前致谢!! 1