【问题标题】:How to overwrite a file in Chrome App?如何覆盖 Chrome 应用程序中的文件?
【发布时间】:2015-02-25 03:51:34
【问题描述】:

我遵循了这个例子:

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'}));
            });
        });
    });
});

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

但是我发现一个问题:如果文件不为空,它们的内容不会被完全覆盖,只会覆盖开头部分。

我需要先删除文件吗?还是我错过了什么?

【问题讨论】:

    标签: javascript google-chrome filesystems google-chrome-app filewriter


    【解决方案1】:

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

    此代码对我有用,通过在写入完成后将文件截断到写入器的位置。

    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'}));
                });
            });
        });
    });
    

    【讨论】:

    • 对我来说,truncate 函数触发了 onwriteend 事件,导致无限循环。但是this solution 为我工作。
    猜你喜欢
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 2016-06-05
    • 2012-09-16
    • 1970-01-01
    • 2016-03-14
    相关资源
    最近更新 更多