xan*_*xan 10 javascript attachment download
我知道这里提到的隐藏的iFrame技巧(http://stackoverflow.com/questions/365777/starting-file-download-with-javascript)和其他答案.
我对类似的问题很感兴趣:
我如何使用Javascript下载当前页面(IE:当前DOM或其中的一些子集)作为文件?
我有一个网页,它从非确定性查询中获取结果(例如随机样本)以显示给用户.我已经可以通过查询字符串参数使页面返回文件而不是呈现页面.我可以添加"获取文件版本"按钮(我们的标准方法),但结果将与显示的结果不同,因为它是查询的不同运行.
有没有办法通过Javascript下载当前页面作为文件,或复制到剪贴板我唯一的选择?
编辑 Stefan Kendall和dj_segfault建议的选项是编写结果服务器端以供以后检索.好主意,但遗憾的是在这种情况下写文件服务器端是不可能的.
如何不寒而栗传递innerHTML的参数后到另一个页面?
Mic*_*Mic 17
您可以尝试使用该协议 data:text/attachment
像:
<html>
<head>
<style>
</style>
</head>
<body>
<div id="hello">
<span>world</span>
</div>
<script>
(function(){
document.location =
'data:text/attachment;,' + //here is the trick
document.getElementById('hello').innerHTML;
//document.documentElement.innerHTML; //To Download Entire Html Source
})();
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
shesek评论后编辑
为了增加Mic上面的极好答案,还有一些额外的要点:
(function(){
document.location =
'data:text/attachment;base64,' + // Notice the new "base64" bit!
utf8_to_b64(document.getElementById('hello').innerHTML);
//utf8_to_b64(document.documentElement.innerHTML); //To Download Entire Html Source
})();
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
Run Code Online (Sandbox Code Playgroud)
通过MDN的utf_to_b64() - 适用于Chrome/FF.
<a onclick="$(this).attr('href', 'data:text/plain;base64,' + utf8_to_b64($('html').clone().find('#generate').remove().end()[0].outerHTML));" download="index.html" id="generate">Generate static</a>
Run Code Online (Sandbox Code Playgroud)
这将下载当前页面的HTML作为index.html并删除用于生成输出的链接.这假设上面的utf8_to_b64()函数在其他地方定义.