Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save multiple files in a chrome app

I am trying to save multiple files to a directory - in one operation. If I correctly understand the chrome fileSystem api documentation this should be possible when I use the openDirectory option for chrome.fileSystem.chooseEntry. Is that even allowed?
However, the documentation is very minimalistic and I also did not find any examples via google.

More background:
I have the proper permissions to access a directory and also have write permissions:

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

Then you are left with chrome.fileSystem.chooseEntry(object options, function callback) and chrome.fileSystem.getWritableEntry(entry entry, function callback), but I did not figure out if these functions are even what I want.

Here is how a single file can be saved to the file system:

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

But how can I save multiple files when I use chrome.fileSystem.chooseEntry({type:"openDirectory",..} or does openDirectory only grant me read-rights?

like image 562
Marco Pashkov Avatar asked Nov 03 '13 22:11

Marco Pashkov


1 Answers

I believe this should work.

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'}));
            });
        });
    });
});
like image 187
Paul Draper Avatar answered Sep 21 '22 11:09

Paul Draper