如何在 chrome 应用中保存多个文件

How to save multiple files in a chrome app

本文关键字:保存 文件 应用 chrome      更新时间:2023-09-26

我正在尝试将多个文件保存到一个目录中 - 在一个操作中。如果我正确理解了chrome文件系统api文档,那么当我使用chrome.fileSystem.chooseEntryopenDirectory选项时,这应该是可能的。这甚至允许吗?
但是,文档非常简约,我也没有通过谷歌找到任何示例。

更多背景:
我具有访问目录的适当权限,并且还具有写入权限:

/*you need chrome >= Version 31.x [currently chrome beta]*/
"permissions": [
    {"fileSystem": ["write", "directory"]}, "storage", 
]

然后你留下chrome.fileSystem.chooseEntry(对象选项,函数回调)和chrome.fileSystem.getWritableEntry(entry entry,函数回调),但我没有弄清楚这些函数是否是我想要的。

以下是将单个文件保存到文件系统的方法:

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);
    }, errorHandler);
}

但是,当我使用 chrome.fileSystem.chooseEntry({type:"openDirectory",..} 时,如何保存多个文件,或者 openDirectory 只授予我读取权限?

我相信这应该有效。

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