我正在使用HTML5 FileWriter API来保存我的webapp状态.我有一些JS定期调用FileWriter.write它(因此,随着时间的推移,该write方法被调用几次).默认情况下,FileWriter API使用'append'方法来编写不符合我需要的文件,因为我不想覆盖文件内容.
我第一次尝试这个:
this._writer.seek(0);
this._writer.write(content);
Run Code Online (Sandbox Code Playgroud)
当您编写的文本短于文件内容时,这不起作用.然后我尝试了这个:
this._writer.truncate(0);
this._writer.write(content);
Run Code Online (Sandbox Code Playgroud)
这段代码应该清除文件,然后编写我的新内容,但是在write调用方法时出现以下错误:
Uncaught InvalidStateError: An operation that depends on state cached in an interface object was made but the state had changed since it was read from disk.
Run Code Online (Sandbox Code Playgroud)
奇怪的是:当我调试代码(带断点)时,不会发生错误,好像FileWriter.truncate是一个异步方法......
我被困在这里,有什么想法吗?
我使用的是Chrome 30.0.1599.69
我想在一个操作中将多个文件保存到目录中.如果我理解正确的铬文件系统的API文档,当我使用这应该是可能openDirectory的选项chrome.fileSystem.chooseEntry.这甚至是允许的吗?
但是,文档非常简约,我也没有通过谷歌找到任何例子.
更多背景:
我有权访问目录并具有写权限:
/*you need chrome >= Version 31.x [currently chrome beta]*/
"permissions": [
{"fileSystem": ["write", "directory"]}, "storage",
]
Run Code Online (Sandbox Code Playgroud)
然后你留下chrome.fileSystem.chooseEntry(对象选项,函数回调)和chrome.fileSystem.getWritableEntry(条目入口,函数回调),但我没有弄清楚这些函数是否是我想要的.
以下是如何将单个文件保存到文件系统:
chrome.fileSystem.chooseEntry({type:"saveFile", suggestedName:"image.jpg"},
function(entry, array){
save(entry, blob); /*the blob was provided earlier*/
}
);
function save(fileEntry, content) {
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
fileWriter.onwriteend = null;
fileWriter.truncate(content.size);
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
var blob = new Blob([content], {'type': 'image/jpeg'});
fileWriter.write(blob); …Run Code Online (Sandbox Code Playgroud)