在< a>上下载属性标记在Chrome中无法使用 [英] download attribute on <a> tag doesn't work in Chrome

查看:115
本文介绍了在< a>上下载属性标记在Chrome中无法使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我点击导出按钮时,chrome会下载一个名为download的文件,其类型为Document。如果我手动添加扩展名(.xls),则下载文件的内容是正确的。我想知道下载属性在这种情况下是如何工作的。这是我的代码:

As I click the export button, chrome will download a file called "download" whose type is "Document". If I add the extension(.xls) manually, the content of the downloaded file is correct. I wonder how does the download attribute work in such a situation. Here is my code:

a = document.createElement("a");
var data_type = 'data:application/vnd.ms-excel,';
var table_div = document.getElementById('table');
var table_html = table_div.outerHTML.replace(/ /g, '%20');
a.download = "excel.xls";
a.href = data_type + table_html;
a.click();

此外,在我尝试了不同的PC之后,其中一些可以使用正确的名称下载文件,与我的一样。而且这个代码在所有机器上都不适用于Firefox。

Moreover, after I tried different PCs, some of them can download the file with the proper name, some are same with mine. And this code is not working for Firefox in all machines.

推荐答案

这应该可行(我以前使用基本相同的代码来处理页面内生成的文件,并且它已经工作),但目前在最新版本的Chrome上存在未解决的问题( https:/ /code.google.com/p/chromium/issues/detail?id=366370 )有关被忽略的下载属性。根据W3C的建议,似乎Chrome的最新版本有意忽略跨源链接上的下载属性(我认为这是一个愚蠢的建议,但仍是一个建议)。 Chrome可能会将data:网址视为跨网站,因此会忽略您的下载属性;如果是这样,几乎没有什么可以做的。

This should work (I have used essentially identical code for in-page-generated files before, and it has worked), but there is currently an open issue on the latest version of Chrome (https://code.google.com/p/chromium/issues/detail?id=366370) concerning the "download" attribute being ignored. It seems that the latest versions of Chrome intentionally ignore the download attribute on cross-origin links according to W3C recommendation (a stupid recommendation in my opinion, but it is a recommendation nonetheless). Chrome might be treating "data:" URLs as cross-origin and thus ignoring your download attribute; if so, there's pretty much nothing you can do about it.

编辑:看起来像是另一个当前的错误,专门处理数据URI: https://code.google.com/p/chromium/issues/detail?id=373182

Looks like there is another current bug addressing data URIs specifically: https://code.google.com/p/chromium/issues/detail?id=373182

所以,是的,你的代码是正确的;这是Chrome中的一个错误。

So, yeah, your code is correct; this is a bug in Chrome.

这篇关于在< a>上下载属性标记在Chrome中无法使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆