unlimited file storage in chrome app

大憨熊 提交于 2019-11-30 10:19:14

First of all, to avoid confusion, what here is being called a "packaged app" should be called a "Chrome App".

If the blob is to be used by any other app, you must obtain a FileEntry via chrome.fileSystem.chooseEntry so the data will be written to the computer's file system where the user can access it. (You can obtain a directory that way from the user and save the retained entry, and use that without asking the user to make a choice every time.)

If the blob is only for use by that Chrome App, you can use the file API without calling chrome.fileSystem.chooseEntry.

As for limits, you're correct that unlimitedStorage allows unlimited storage. In my experiments, despite the documentation, I have never been able to get a Chrome App to ask the user to authorize a specific amount. I use that permission, and there seems to be no limit. The Google documentation I've read on this appears to be inaccurate.

If you're writing to the external file system, after you've called chrome.fileSystem.chooseEntry, there are no limits and you don't need unlimitedStorage permission.

markain

My solution.

main.js

var chooseDirectory = function() {
  chrome.app.window.create("choose_directory.html");
};

chrome.runtime.onInstalled.addListener(function(details) {
  if (details.reason == 'install') {
    chooseDirectory();
  }
};  

chrome.runtime.onMessageExternal.addListener(function(message, sender, sendResponse) {

  switch (message.type) {
  case 'saveBlob':
    var blob = new Blob([message.blob])

    chrome.storage.local.get('filesystemKey', function(items) {
      var fileSystemRef = items.fileSystemKey;

      chrome.fileSystem.restoreEntry(fileSystemRef, function(fileSystem) {

        fileSystem.getFile('test.txt', { create: true }, function(fileEntry) {

          fileEntry.createWriter(function(writer) {
            writer.write(blob);
          });   
        });             
      });           
    });  
    break;
  } 
});

after using the chrome filesystem APIs, you use the regular html5 filesystem API to create the file. As explained here you cannot call the chooseDirectory function from the background script, so you need to create an app window that can call it, which I do below.

choose_directory.js

window.addEventListener('load', function() {

  document.getElementById('input').addEventListener('click', function() {

    chrome.fileSystem.chooseEntry({type: 'openDirectory'}, function(entry) {
      var homeDirectory = chrome.fileSystem.retainEntry(entry);

      chrome.storage.local.set({'filesystemKey': homeDirectory}, function() {
        window.close();
      });           
    });     
  });   
}); 

choose_directory.html

<script src="choose_directory.js"></script>

You need to choose a directory where you will store your files.

<button id="input"> Chose a place to save your files</button> 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!