我正在尝试使用 http 链接下载文件。 这是代码:
downloadFile: function (fileName, url) {
var link = document.createElement('a');
link.setAttribute('download', fileName);
link.setAttribute('type', 'application/octet-stream');
link.target = '_blank';
link.href = url;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
这适用于 Chrome 和 Edge,但不适用于 Firefox。 当我尝试下载文本文件或图像时,浏览器会打开一个新选项卡,其中显示文件内容。我需要浏览器打开默认下载窗口。
可能吗?
这是我使用的 URL 示例:http://localhost:17671/docstmp/528d149e37467a53faeeeb0556901d87/ToDo.txt
我创建了这个 jsfiddle 来演示:jsfiddle.net/hp7yod85
最佳答案
请求的资源没有Access-Control-Allow-Origin
header 集,并且有 X-Frame-Options
header 设置为 SAMEORIGIN
防止加载到 <iframe>
元素。
您可以使用 YQL
检索内容,然后创建 data URL
返回结果中的文本内容,然后创建 <a>
元素为 href
设置为data URL
。返回打开对话框的预期结果,提示在文本编辑器中打开文件或在 firefox 47 中保存文件。
<!DOCTYPE html>
<html>
<body>
<button onclick="downloadFile()">Test</button>
<script>
function downloadFile() {
var request = new XMLHttpRequest();
var url = 'https://query.yahooapis.com/v1/public/yql?q='
+ 'select * from html where '
+ 'url="http://www.ietf.org/rfc/bcp/bcp47.txt"&format=json&callback='
request.open("GET", url);
request.onload = function() {
var data = JSON.parse(this.responseText).query.results.body.content;
var a = document.createElement("a");
a.href = "data:text/plain," + data;
a.download = "bcp47.txt";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
request.send()
}
</script>
</body>
</html>
关于javascript - 下载文本文件或图像在 Firefox 上抛出 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38312153/