Javascript Blob createObjectURL 下载在 Firefox 中不起作用(但在调试时有效)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30694453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:36:56  来源:igfitidea点击:

Blob createObjectURL download not working in Firefox (but works when debugging)

javascriptfirefoxdownloadblob

提问by Johncl

I have an odd problem, the function below is one I created based on what i found on the net about creating a Blob in the client on the fly with some binary data in (passed as an array) and being able to download that. This works brilliantly in Chrome, but doesn't do anything in Firefox - UNLESS I debug and step through the code. Yes, oddly, if I create a break point inside the function and step through it, the a.click() will bring up the download window!

我有一个奇怪的问题,下面的函数是我根据我在网上找到的关于使用一些二进制数据(作为数组传递)在客户端中动态创建 Blob 并能够下载它的内容创建的函数。这在 Chrome 中非常有效,但在 Firefox 中不起作用 - 除非我调试并逐步执行代码。是的,奇怪的是,如果我在函数内部创建一个断点并单步执行,a.click() 将打开下载窗口!

function downloadFile(filename, data) {

    var a = document.createElement('a');
    a.style = "display: none";  
    var blob = new Blob(data, {type: "application/octet-stream"});
    var url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);    
}

Can anyone help me? This was tested using Firefox 38.0.5.

谁能帮我?这是使用 Firefox 38.0.5 测试的。

回答by Musa

You're probably removing the resource too soon, try delaying it

您可能过早地移除资源,请尝试延迟它

    ...
    a.click();
    setTimeout(function(){
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);  
    }, 100);  
}

回答by Tomek

The above didn't solve the issue for me. But this one did instead:
Programmatical click on <a>-tag not working in Firefox
It was a problem with the triggering click event, not premature removal of the resource.

以上没有为我解决问题。但是这个却做到了:
<a>-tag 上的编程点击在 Firefox 中不起作用
这是触发点击事件的问题,而不是过早删除资源。

回答by Azad

this solution works for me in bot chrome and firefox for existing anchor element to download binary file

这个解决方案适用于我在 bot chrome 和 firefox 中为现有锚元素下载二进制文件

window.URL = window.URL || window.webkitURL;

var blob = new Blob([new Uint8Array(binStream)], {type: "octet/stream"});

var link = document.getElementById("link");
link.href = window.URL.createObjectURL(blob);