2014 年 4 月 24 日,W3C 正式将 FileSystem API 成熟为 Working Group Note,使用此技术进行开发时应谨慎,不确定是否或如何很长一段时间它会一直存在。
IndexedDB 有望成为一个有前途的替代方案/解决方法,或许可以查看html5 rocks tutorial。在下面留下我最初的答案,因为它仍然有效,但想对文件系统 API 提出警告。
我看到你得到了答案,但我想为文件系统 api(你也问过)提供一个解决方案 使用 cookie,你有大小限制,但要回答你问题的另一面,下面是
article I used to get started with the HTML5 File-system API
文件系统 api 中的所有其他内容都围绕获取对文件的引用,然后创建写入器、读取器等。特定于该文件实例。当文件写入器、读取器、引用完成加载时,将传递/执行回调函数。
请求存储配额/获取对文件系统的引用
var onInitFs = function(fs){
fileSystem = fs;//set global reference to the filesystem
};
var errorHandler = function(e){console.log('Error', e);};
navigator.webkitPersistentStorage.requestQuota(1024*1024*1024*5, function(grantedBytes) {
window.webkitRequestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler);
}, errorHandler);
制作文件
fileSystem.root.getFile("filepathtoJSON", {
create: true
}, callback, errorHandler);
将 JSON 写入文件
fileSystem.root.getFile("filepathtoJSON", {create: true}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.onwriteend = function(e) {
writer.onwriteend = function(e){
callbackFunction();
}
writer.onerror = function(e3){console.log(e3);}
var blob = new Blob([JSON.stringify(targetJSONobj)]);
writer.write(blob);
};
writer.onerror = function(e3) {console.log(e3);};
writer.truncate(0);
}, errorHandler);
}, errorHandler);
从文件中读取 JSON/创建 fileReader(在回调函数中传递 JSON 对象)
fileSystem.root.getFile("filepathtoJSON", {creation:false}, function(fileEntry){
fileEntry.file(function(file){
var reader = new FileReader();
reader.onloadend = function(e) {
callback(JSON.parse(this.result));
};
reader.readAsText(file);
}, errorHandler)
}, errorHandler);