在Chrome应用程序中删除文件后访问fileEntry

Access fileEntry after dropping a file in a Chrome App

本文关键字:访问 fileEntry 文件 删除 Chrome 应用程序      更新时间:2023-09-26

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

我得到这样的文件:

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

我想做什么

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

正如我所说:我已经得到了文件的内容,但我不能把更改写回文件,因为我需要一个fileEntry对象,以便这样做。

好的,我只是在检查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...
    });
});