例如,如果你点击链接:

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

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


当前回答

使用服务工作者,这最终在真正意义上成为可能。

创建一个假URL。例如/saveAs/myPrettyName.jpg 在<a href, <img src,窗口中使用URL。open(url),绝对可以用“真正的”url做任何事情。 在worker内部,捕获fetch事件,并用正确的数据进行响应。

浏览器现在会建议myPrettyName.jpg,即使用户在一个新的选项卡打开文件,并试图保存它。这将完全像文件来自服务器一样。

// In the service worker
self.addEventListener( 'fetch', function(e)
{
    if( e.request.url.startsWith( '/blobUri/' ) )
    {
        // Logic to select correct dataUri, and return it as a Response
        e.respondWith( dataURLAsRequest );
    }
});

其他回答

我在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

看看这个链接: http://lists.w3.org/Archives/Public/uri/2010Feb/0069.html

引用:

它甚至可以在末尾使用;base64(也就是说,不会引起问题) 像这样(至少在Opera中): 数据:文本/平原;charset = utf - 8;头= 3附加% % 20附件% 3 b % 20文件名以% 20 spaces.txt % % 3 d % 22 22% 0 3 d % 0 acontent-language % % 20 en; base64 4 oiadqo % 3 d

也有一些信息在讨论的其他消息。

下面是一个基于Holf版本的jQuery版本,可用于Chrome和Firefox,而他的版本似乎只适用于Chrome。在身体上添加一些东西来做到这一点有点奇怪,但如果有人有更好的选择,我完全支持。

var exportFileName = "export-" + filename;
$('<a></a>', {
    "download": exportFileName,
    "href": "data:," + JSON.stringify(exportData, null,5),
    "id": "exportDataID"
}).appendTo("body")[0].click().remove();

Chrome使这非常简单:

function saveContent(fileContents, fileName)
{
    var link = document.createElement('a');
    link.download = fileName;
    link.href = 'data:,' + fileContents;
    link.click();
}

谷歌代码上有一个小的变通脚本,对我有用:

http://code.google.com/p/download-data-uri/

它添加一个包含数据的表单,提交该表单,然后再次删除该表单。很粗糙,但对我来说很管用。需要jQuery。

这个线程出现在谷歌谷歌代码页之前,我认为它可能有帮助,在这里也有链接。