如何在Chrome App中覆盖文件?

Fre*_*ind 6 javascript filesystems google-chrome filewriter google-chrome-app

我按照这个例子:

chrome.fileSystem.chooseEntry({type:'openDirectory'}, function(entry) {
    chrome.fileSystem.getWritableEntry(entry, function(entry) {
        entry.getFile('file1.txt', {create:true}, function(entry) {
            entry.createWriter(function(writer) {
                writer.write(new Blob(['Lorem'], {type: 'text/plain'}));
            });
        });
        entry.getFile('file2.txt', {create:true}, function(entry) {
            entry.createWriter(function(writer) {
                writer.write(new Blob(['Ipsum'], {type: 'text/plain'}));
            });
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

覆盖一些现有的文件file1.txtfile2.txt.

但是我发现了一个问题:如果文件不是空的,它们的内容将不会被完全覆盖,只会覆盖起始部分.

我需要先删除文件吗?或者我会错过什么?

Sar*_*lan 4

它看起来只覆盖指定位置write的文件内容,所以你是正确的,如果你想完全替换文件的文本,你需要先删除文件或截断它们。

这段代码对我有用,在写入完成后将文件截断到写入者的位置。

chrome.fileSystem.chooseEntry({type:'openDirectory'}, function(entry) {
    chrome.fileSystem.getWritableEntry(entry, function(entry) {
        entry.getFile('file1.txt', {create:true}, function(entry) {
            entry.createWriter(function(writer) {
                writer.onwriteend = function(e) {
                    e.currentTarget.truncate(e.currentTarget.position);
                };
                writer.write(new Blob(['Lorem'], {type: 'text/plain'}));
            });
        });
        entry.getFile('file2.txt', {create:true}, function(entry) {
            entry.createWriter(function(writer) {
                writer.onwriteend = function(e) {
                    e.currentTarget.truncate(e.currentTarget.position);
                };
                writer.write(new Blob(['Ipsum'], {type: 'text/plain'}));
            });
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,截断函数触发了 onwriteend 事件,导致无限循环。然而[这个解决方案](http://stackoverflow.com/questions/19426698/overwrite-a-file-with-html5-filewriter)对我有用。 (4认同)