javascript 下载 HTML 格式的文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23950753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download a text file in HTML
提问by thilinistg
I want to write a html code to enable downloading a user entered input value saved in a text file. As in the below html, when the 'Save' button is pressed, the input value should save in the user computer as a .text file.
我想编写一个 html 代码来下载保存在文本文件中的用户输入的输入值。在下面的 html 中,当按下“保存”按钮时,输入值应作为 .text 文件保存在用户计算机中。
<html>
<head>
<script type="text/javascript">
function write_below(form) {
var input = document.forms.write.input_to_write.value;
document.getElementById('write_here').innerHTML = "Your input was:" + input;
return false;
}
</script>
</head>
<!--Insert more code here-->
<body>
<form name='write' onsubmit='return write_below(this);'>
<input type="text" name='input_to_write'>
<input type="button" value="save" />
</form>
<div id='write_here'></div>
</body>
</html>
Can anyone help me in this problem?
谁能帮我解决这个问题?
回答by CodeColorist
The data URI scheme is a URI scheme (Uniform Resource Identifier scheme) that provides a way to include data in-line in web pages as if they were external resources.
数据 URI 方案是一种 URI 方案(统一资源标识符方案),它提供了一种将数据嵌入网页中的方法,就好像它们是外部资源一样。
You can use following uri to emulate an external text file. Just copy the code to your address bar to see what would happen.
您可以使用以下 uri 来模拟外部文本文件。只需将代码复制到您的地址栏,看看会发生什么。
data:application/txt,Hello World!
data:application/txt,Hello World!
Full code or check out this fiddle:
完整代码或查看此小提琴:
<html>
<head>
<title>Fake download via datauri</title>
</head>
<body>
<textarea cols="50" rows="10" id="source">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>
<br>
<button type="button" id="save" title="Save as text file">Save</button>
<script type="text/javascript">
// when document is ready
document.getElementById("save").onclick = function() {
// when clicked the button
var content = document.getElementById('source').value;
// a [save as] dialog will be shown
window.open("data:application/txt," + encodeURIComponent(content), "_self");
}
</script>
</body>
</html>
Some old fashioned browsers don't support this feature. Full list
一些老式浏览器不支持此功能。完整列表
Besides, make sure the content isn't too long in case your browser rejects the request.
此外,请确保内容不会太长,以防您的浏览器拒绝请求。
回答by Sebastien C.
You can do that by creating a blob-url and a link to it. The link (and not a button !) is necessary to have the download
attribute, which specifies the default name of the file.
你可以通过创建一个 blob-url 和一个链接来做到这一点。链接(而不是按钮!)是具有download
指定文件默认名称的属性所必需的。
However, because I'm not sure of the compatibility of this attribute, I set a binary mime type because text/plain
is known by the browsers and just opened instead of showing the download window.
但是,因为我不确定这个属性的兼容性,所以我设置了一个二进制 mime 类型,因为text/plain
浏览器知道它并且只是打开而不是显示下载窗口。
var text = "foo\nbar\nbaz";
var fileBlob = new Blob([text], {type: "application/octet-binary"});
var link = document.createElement("a");
link.setAttribute("href", URL.createObjectURL(fileBlob));
link.setAttribute("download", "HelloWorld.txt");
link.appendChild(document.createTextNode("Save file"));
document.body.appendChild(link);
回答by ReNiSh A R
By using the foloowing PHP function you can download files:
通过使用以下 PHP 函数,您可以下载文件:
function dowld($path)
{
// get the file mime type using the file extension
$mime = get_mime_by_extension($path); // Build the headers to push out the file properly.
header('Content-Description: File Download');
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Type: '.$mime);
header('Content-Disposition: attachment; filename="'.basename($path).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
ob_clean();
flush();
readfile($path);
}
$pathrefers to the path to the file to download.
$path指的是要下载的文件的路径。
Eg:
例如:
dowld('./files/myfile.txt');