我在blob创建行上得到一个InvalidStateError即11。不用说,它适用于Chrome和Firefox。 我可以看到二进制数据是我的客户端。有没有其他方法可以将其下载为文件?
var request= new ActiveXObject("MicrosoftXMLHTTP");
request.open("post", strURL, true);
request.setRequestHeader("Content-type","text/html");
addSecureTokenHeader(request);
request.responseType = 'blob';
request.onload = function(event) {
if (request.status == 200) {
var blob = new Blob([request.response], {type: 'application/pdf'});
var url = URL.createObjectURL(blob);
var link = document.querySelector('#sim');
link.setAttribute('href', url);
var filename = request.getResponseHeader('Content-Disposition');
$('#sim').attr("download", filename);
$(link).trigger('click');
fireEvent(link,'click');
}else {
//handle error
}
}
答案 0 :(得分:3)
花了一些时间,实际上发现添加new Uint8Array
有效:
var blob = new Blob([new Uint8Array(request.response)], {type: 'application/pdf'});
答案 1 :(得分:3)
在实例化XmlHttpRequest对象后立即设置xhr.responseType =“ blob”以获取InvalidStateError之后,
xhr.responseType = "blob"
到
xhr.onloadstart = function(ev) {
xhr.responseType = "blob";
}
为我解决了! :)
答案 2 :(得分:2)
不是一种优雅的方式,但它适用于IE8 - IE11:
var myForm = document.createElement("form");
myForm.method = "POST";
myForm.action = strURL;
myForm.target = "_blank";
var myInput = document.createElement("input");
myInput.type = "text";
myInput.name = "sim";
myInput.value = JSON.stringify(/*data to post goes here*/);
myForm.appendChild(myInput);
document.body.appendChild(myForm);
myForm.submit();
$(myForm).hide();
答案 3 :(得分:1)
在这种情况下,您需要使用BlobBuilder。
来自:https://github.com/bpampuch/pdfmake/issues/294#issuecomment-104029716
try {
blob = new Blob([result], { type: 'application/pdf' });
}
catch (e) {
// Old browser, need to use blob builder
window.BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder;
if (window.BlobBuilder) {
var bb = new BlobBuilder();
bb.append(result);
blob = bb.getBlob("application/pdf");
}
}
答案 4 :(得分:0)
经过大量搜索,这对我在 IE、Edge 和 Chrome 上都有效
var xhr = new XMLHttpRequest();
xhr.onloadstart = function (ev) {
xhr.responseType = "blob";
};
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
if (!window.navigator.msSaveOrOpenBlob) {
var url = (window.URL || window.webkitURL).createObjectURL(xhr.response);
var aLink = document.createElement("a");
document.body.appendChild(aLink);
aLink.href = url;
aLink.download = filename;
aLink.click();
} else {
var fileData = [xhr.response];
blobObject = new Blob(fileData);
window.navigator.msSaveOrOpenBlob(blobObject, filename);
}
}
};