例如,如果你点击链接:

数据:应用程序/八进制;base64 SGVsbG8 =

浏览器将提示您下载一个文件,该文件由超链接本身中base64所包含的数据组成。是否有办法在标记中建议一个默认名称?如果不是,是否有JavaScript解决方案?


当前回答

下面的Javascript代码片段通过使用链接的新“下载”属性并模拟点击在Chrome中工作。

function downloadWithName(uri, name) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  link.click();
}

下面的例子展示了它的使用:

downloadWithName("data:,Hello%2C%20World!", "helloWorld.txt")

其他回答

下面的Javascript代码片段通过使用链接的新“下载”属性并模拟点击在Chrome中工作。

function downloadWithName(uri, name) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  link.click();
}

下面的例子展示了它的使用:

downloadWithName("data:,Hello%2C%20World!", "helloWorld.txt")

您可以向锚元素添加一个下载属性。

示例:

<a download="abcd.cer"
    href="data:application/stream;base64,MIIDhTC......">down</a>

根据RFC 2397,没有。

<a>元素似乎也没有任何可以使用的属性。

然而,HTML5随后在<a>元素上引入了下载属性,尽管在编写时支持并不普遍(例如,没有MSIE支持)。

我在firefox的network /protocol/data/nsDataHandler.cpp中查找了一些

数据处理程序只解析内容/类型和字符集,并查看是否有“;base64” 在字符串中

RFC没有指定文件名,至少firefox没有为它处理文件名, 代码生成一个随机名称加上".part"

我也检查了firefox日志

[b2e140]: DOCSHELL 6e5ae00 InternalLoad data:application/octet-stream;base64,SGVsbG8=
[b2e140]: Found extension '' (filename is '', handling attachment: 0)
[b2e140]: HelperAppService::DoContent: mime 'application/octet-stream', extension ''
[b2e140]: Getting mimeinfo from type 'application/octet-stream' ext ''
[b2e140]: Extension lookup on '' found: 0x0
[b2e140]: Ext. lookup for '' found 0x0
[b2e140]: OS gave back 0x43609a0 - found: 0
[b2e140]: Searched extras (by type), rv 0x80004005
[b2e140]: MIME Info Summary: Type 'application/octet-stream', Primary Ext ''
[b2e140]: Type/Ext lookup found 0x43609a0

如果你想看mozilla源代码,这些文件很有趣:

data uri handler: netwerk/protocol/data/nsDataHandler.cpp
where mozilla decides the filename: uriloader/exthandler/nsExternalHelperAppService.cpp
InternalLoad string in the log: docshell/base/nsDocShell.cpp

我认为你现在可以停止寻找解决方案了,因为我怀疑没有解决方案:)

正如在这个线程中注意到的,html5有下载属性,它也适用于firefox 20 http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#attr-hyperlink-download

仅限HTML:使用download属性:

<a download="logo.gif" href="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">下载透明png</a> .gif


仅Javascript:你可以用这段代码保存任何数据URI:

function saveAs(uri, filename) { var link = document.createElement('a'); if (typeof link.download === 'string') { link.href = uri; link.download = filename; //Firefox requires the link to be in the body document.body.appendChild(link); //simulate click link.click(); //remove the link when done document.body.removeChild(link); } else { window.open(uri); } } var file = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7' saveAs(file, 'logo.gif');

Chrome、Firefox和Edge 13+将使用指定的文件名。

IE11、Edge 12和Safari 9(它们不支持下载属性)将用默认名称下载文件,或者简单地在新选项卡中显示,如果文件类型是受支持的:图像、视频、音频文件……