Chrome应用:如何在后台将blob内容保存到fileSystem?

时间:2015-12-30 14:29:02

标签: javascript angularjs google-chrome google-chrome-app html5-filesystem

在Chrome应用中,我使用JavaScript XHR从服务器下载blob内容(特别是Angular $ http GET,响应类型为'blob')

我应该如何将其保存到chrome应用程序的文件系统?

目前在HTML5文件系统API上使用Angular包装器 https://github.com/maciel310/angular-filesystem

我不想向用户显示弹出窗口(因此我无法使用chrome.fileSystem. chooseEntry

chrome.fileSystem.requestFileSystem API仅受Kiosk专用应用支持。 因此我使用HTML5 FileSystem API而不是chrome。

我正在使用以下代码来使XHR获取blob。

 $http({
          url: SERVER_URL+"/someVideo.mp4",
          method: "GET",
          responseType: "blob"
      }).then(function(response) {
          console.log(response);
          fileSystem.writeBlob(response.name, response).then(function() {
             console.log("file saved");
          }, function(err) {
              console.log(err);
          });
      }, function (response) {

      });

这是我的writeBlob方法

writeBlob: function(fileName, blob, append) {
    append = (typeof append == 'undefined' ? false : append);

    var def = $q.defer();

    fsDefer.promise.then(function(fs) {

        fs.root.getFile(fileName, {create: true}, function(fileEntry) {

            fileEntry.createWriter(function(fileWriter) {
                if(append) {
                    fileWriter.seek(fileWriter.length);
                }

                var truncated = false;
                fileWriter.onwriteend = function(e) {
                    //truncate all data after current position
                    if (!truncated) {
                        truncated = true;
                        this.truncate(this.position);
                        return;
                    }
                    safeResolve(def, "");
                };

                fileWriter.onerror = function(e) {
                    safeReject(def, {text: 'Write failed', obj: e});
                };

                fileWriter.write(blob);

            }, function(e) {
                safeReject(def, {text: "Error creating file", obj: e});
            });

        }, function(e) {
            safeReject(def, {text: "Error getting file", obj: e});
        });

    }, function(err) {
        def.reject(err);
    });

    return def.promise;
},

这会将SECURITY_ERR显示为It was determined that certain files are unsafe for access within a Web application, or that too many calls are being made on file resources.

这是什么解决方案?

我在启动应用时尝试使用--allow-file-access-from-files标志。它没有帮助。

2 个答案:

答案 0 :(得分:2)

Chrome应用程序的沙箱存储不允许将文件存储在根目录中(即/

修改代码以将其保存在其下的特定子目录中。 例如 -

fileSystem.writeBlob("/new"+response.name, response).then(function() {
             console.log("file saved");
          }, function(err) {
              console.log(err);
          });

这会将文件成功保存在/new/目录下。

答案 1 :(得分:0)

为了对此进行扩展,这里有一个关于如何下载文件并保存blob并将其显示回用户的完整示例应用程序。

https://github.com/PierBover/chrome-os-app-download-example