FileSystemApi和writableStream

问题描述

我正在尝试使用FileSystem API,使用FileSystem API将SPA上的已上传文件写入本地沙盒FileSystem

文件是通过drop acion上传的,我可以在回调中获得File对象数组。 从File可以得到ReadableStream调用stream方法(是的,它只返回可读的代码)。

考虑到上传文件可能足够大,我将进行流传输,而不是将其完全加载到blob中,然后写入FileSystem api。

因此,按照文档进行操作的步骤是:

  1. 通过异步FileSystem调用获取webkitRequestFileSystem(DOMFileSystem)。
  2. 获取作为FileSystemDirectoryEntry的道具root
  3. 通过getFile(带有标志create:true)创建一个文件,该文件返回(异步)一个FileSystemFileEntry

现在从FileEntry中,我可以使用createWriter获取FileWriter,但是它已经过时了(在MDN中),无论如何它都是FileWriter,而我希望依次获取WritableStream使用上载文件Handler-> ReadableStream中的pipeto

因此,我看到在控制台中定义了类(接口)FileSystemFileHandler,但是我不明白如何从FileSystemFileEntry获取实例。如果可以获取FileSystemFileHandler,则可以调用createWritable获取FileSystemWritableFileStream,可以通过ReadStream对其进行“管道传输”。

任何人都可以弄清楚这个烂摊子吗?

参考: https://web.dev/file-system-access/ https://wicg.github.io/file-system-access/#filesystemhandle https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileEntry

解决方法

您在底部的“引用”链接中找到了解决方案。具体来说,这是要读的section。您可以像这样创建文件或目录:

// In an existing directory,create a new directory named "My Documents".
const newDirectoryHandle = await existingDirectoryHandle.getDirectoryHandle('My Documents',{
  create: true,});
// In this new directory,create a file named "My Notes.txt".
const newFileHandle = await newDirectoryHandle.getFileHandle('My Notes.txt',{ create: true });

一旦有了文件句柄,就可以通过管道对其进行处理或对其进行写入:

async function writeFile(fileHandle,contents) {
  // Create a FileSystemWritableFileStream to write to.
  const writable = await fileHandle.createWritable();
  // Write the contents of the file to the stream.
  await writable.write(contents);
  // Close the file and write the contents to disk.
  await writable.close();
}

…或…

async function writeURLToFile(fileHandle,url) {
  // Create a FileSystemWritableFileStream to write to.
  const writable = await fileHandle.createWritable();
  // Make an HTTP request for the contents.
  const response = await fetch(url);
  // Stream the response into the file.
  await response.body.pipeTo(writable);
  // pipeTo() closes the destination pipe by default,no need to close it.
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...