【问题标题】:Access fileEntry after dropping a file in a Chrome App在 Chrome 应用程序中拖放文件后访问 fileEntry
【发布时间】:2015-09-01 18:23:48
【问题描述】:

是否可以通过拖放打开文件在 Chrome 应用程序中获取 fileEntry 对象?当我将文件放入我的应用程序时,我只会得到一个似乎与文件系统无关的 file 对象。更改后我无法使用该对象来保存文件。

我得到这样的文件:

document.body.addEventListener('drop', function (event) {
    file = event.dataTransfer.files[0]
});

我想做什么

我正在开发一个文本编辑器,我想添加一个功能来通过将文件拖到我的应用程序中来打开它。

正如我所说:我已经获得了文件的内容,但我无法将更改写回文件,因为我需要一个 fileEntry 对象才能这样做。

【问题讨论】:

    标签: javascript google-chrome drag-and-drop google-chrome-app file-access


    【解决方案1】:

    好的,我在检查 event 对象时发现了它。在事件对象中有一个名为webkitGetAsEntry() 的函数来获取fileEntry 对象。这是正确的代码:

    document.body.addEventListener('drop', function (event) {
        fileEntry = event.dataTransfer.items[0].webkitGetAsEntry();
    });
    

    这是您可以用来将更改写回文件系统的对象。

    参考代码:

    // Of course this needs the "fileSystem" permission.
    
    // Dropped files from the file system aren't writable by default.
    // So we need to make it writable first.
    chrome.fileSystem.getWritableEntry(fileEntry, function (writableEntry) {
        writableEntry.createWriter(function (writer) {
            // Here use `writer.write(blob)` to write changes to the file system.
            // Very important detail when you write files:
            // https://developer.chrome.com/apps/app_codelab_filesystem
            // look for the part that reads `if (!truncated)`
            // This also is very hard to find and causes an annoying error
            //   when you don't know how to correctly truncate files
            //   while writing content to the files...
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2013-03-06
      • 2015-03-01
      • 1970-01-01
      • 2016-02-16
      • 2012-07-31
      • 1970-01-01
      • 2010-09-09
      相关资源
      最近更新 更多