问题描述
我正在尝试使用FileSystem API,使用FileSystem API将SPA上的已上传文件写入本地沙盒FileSystem。
文件是通过drop acion上传的,我可以在回调中获得File
对象数组。
从File
可以得到ReadableStream
调用stream
方法(是的,它只返回可读的代码)。
考虑到上传的文件可能足够大,我将进行流传输,而不是将其完全加载到blob中,然后写入FileSystem api。
因此,按照文档进行操作的步骤是:
- 通过异步
FileSystem
调用获取webkitRequestFileSystem
(DOMFileSystem)。 - 获取作为FileSystemDirectoryEntry的道具
root
- 通过
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.
}