【发布时间】:2014-12-30 12:57:52
【问题描述】:
我已经在一个项目上工作了几个月,现在已经接近尾声了。最后的步骤之一是提供一个文件,该文件将填充由用户在会话期间的操作生成的信息。 Can I write files with HTML5/JS? ecmanaut 的回答让我非常接近,因为他提供了两种方法,一种是纯 html5,另一种是使用 JavaScript。
我最初使用的 JavaScript 方法只能在 Chrome 中使用,而不能在 Mozilla 或 IE 中使用。所以我使用纯 html5 方法结合一些备用 JavaScript 将其粘贴到页面上,这样它就可以点击了。
document.getElementById('download').innerHTML = '<a id="save" download="earth.txt" href="data:text/plain,mostly harmless and a bit more">Save</a>';
此代码创建一个已下载的文件,但不包含文章所说的换行符' '。所以我做了一个搜索,看看还有哪些其他的字符代码可以被识别。 http://en.wikipedia.org/wiki/Newline 为我提供了许多可能的选择,但我尝试过的都没有。我试过的是:' ',' ', ' ', ' '、'\r\n'、'\r'、'\n'、'\cr'、'\c\r'、0x0D、0x0A、0c0D0A。在许多情况下,换行符被删除并且什么都不会出现。
在测试上述代码时,它可以在 Mozilla 和 Chrome 中运行(减去换行符),但在 IE 中的结果不同。当您点击 Save 链接时,它实际上会移动到页面,并以 url 作为数据内容。
虽然该项目在没有此功能的情况下可能是可以接受的,但我非常希望在花费了这么多时间和精力并且已经如此接近之后让它工作。我还需要在 Safari 中对此进行测试,但我还没有在该浏览器中进行任何测试。所需的浏览器支持从最重要到最不重要如下:Mozilla、Chrome、Safari、IE。如果可能的话,我想避免浏览器特定的编码。
我还应该提到,就像在第一个链接中一样,我不想发送到服务器进行下载,我需要它在客户端本地工作而没有服务器交互。
总而言之,我至少需要让换行符为文件工作,以便 Mozilla 和 Chrome 都可以正常工作。如果可能的话,还有一种让文件在 IE 中工作的方法。
编辑:当地时间 2014 年 11 月 3 日下午 1:40 我已经尝试了 maths4js 建议的关于改变我的报价的编辑,但该建议没有奏效。我注意到提交更大的代码示例页面将是一个有用的想法。也有人建议我看看哪些浏览器支持这个功能http://caniuse.com/#feat=download,看来 IE 和 Safari 不支持,所以我现在不会担心它们,也许以后会有浏览器特定的编码。
<!DOCTYPE HTML>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><style>body{margin: 0px;padding: 0px;}</style></head><body><center><br><div id='download'></div></center>
<script>
function download(){
//var newline= '
'; //no line breaks
//var newline= ' '; //no line breaks
//var newline= " "; //no line breaks
//var newline= "
"; //no line breaks
//var newline= "\r\n"; //no line breaks
//var newline= "\r\n;"; //appends ; but no line breaks
//var newline = '\n'; //no line break
//var newline = '/n'; //completely failed
var newline = 0x0D0A;
var tab = " ";
var text = "Title of the document" + newline;
text += "Just a line of text : ";
text = text +"Random";
text = text + newline + "Trial" + tab + "Time" + tab + "Correct" + newline;
//document.getElementById('download').innerHTML = '<a id="save" download="This_File.txt" href="data:text/plain,'+text+'">Save</a>';
//document.getElementById('download').innerHTML = '<a id="save" download="earth.txt" href="data:text/plain,mostly harmless and a bit more">Save</a>';
document.getElementById('download').innerHTML = "<a id='save' download='earth.txt' href='data:text/plain,mostly harmless and a bit more'>Save</a>";
}
download();
</script>
</body>
</html>
感谢大家为我付出的努力和时间。
【问题讨论】:
-
html5 解决方案当然只适用于支持下载属性的浏览器。
标签: javascript html newline download