您可以通过 Javascript 保存/加载文件吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17956343/
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
Can you save/load a file via Javascript?
提问by Canvas
I want to create a very simple Javascript game using HTML5 (Canvas). But is it possible to save a simple .txt file and load a simple .txt file. I just need to store like the some simple integers. But I just want to know if javascript is allowed to save and load an external file?
我想使用 HTML5 (Canvas) 创建一个非常简单的 Javascript 游戏。但是是否可以保存一个简单的 .txt 文件并加载一个简单的 .txt 文件。我只需要像一些简单的整数一样存储。但我只想知道是否允许 javascript 保存和加载外部文件?
Canvas
帆布
采纳答案by MatteoSp
On Chrome, you can rely on the FileSystem API (for an intro take a look here). Probably other browsers will soon add support to it.
在 Chrome 上,您可以依赖 FileSystem API(有关介绍,请查看此处)。可能其他浏览器很快就会添加对它的支持。
But, if your need is just "to store like the some simple integers" I would consider local storage.
但是,如果您的需求只是“像一些简单的整数一样存储”,我会考虑local storage。
回答by Alex
Since html5 you can use the LocalStorage API. Nowadays almost all browsers support it:
从 html5 开始,您可以使用 LocalStorage API。现在几乎所有浏览器都支持它:
// Check if it is supported in your browser
function supports_html5_storage()
{
try
{
return 'localStorage' in window && window['localStorage'] !== null;
}
catch (e)
{
return false;
}
}
//make use of it:
if( supports_html5_storage() == true )
{
localStorage.setItem("myItem", "myData");
var myDataString = localStorage.getItem("myItem");
alert(myDataString);
}
回答by gwg
In short, no. According David Flanagan's "JavaScript: The Definitive Guide":
简而言之,没有。根据 David Flanagan 的“JavaScript:权威指南”:
Input and output (as well as more sophisticated features, such as networking, storage, and graphics) are the responsibility of the 'host environment' within which JavaScript is embedded.
输入和输出(以及更复杂的功能,如网络、存储和图形)是嵌入 JavaScript 的“宿主环境”的责任。
The bigger question is why. Think about how dangerous it would be if JavaScript could write files to your hard drive. What if any website you visited could access your local file system?
更大的问题是为什么。想想如果 JavaScript 可以将文件写入您的硬盘驱动器会有多危险。如果您访问的任何网站可以访问您的本地文件系统怎么办?
回答by Damiaan Dufaux
You can't access the local file system directly with javascript, but it is possible when you let the user interact (for example by letting the user select a file to upload). See http://www.html5rocks.com/en/tutorials/file/dndfiles/
您无法使用 javascript 直接访问本地文件系统,但是当您让用户交互时(例如让用户选择要上传的文件),这是可能的。见http://www.html5rocks.com/en/tutorials/file/dndfiles/
Another possibility is local storage. See http://davidwalsh.name/html5-storage, http://www.w3.org/TR/webstorage/
另一种可能性是本地存储。见http://davidwalsh.name/html5-storage, http://www.w3.org/TR/webstorage/