【问题标题】:How to create file in the local fs using modern FileApi?如何使用现代 FileApi 在本地 fs 中创建文件?
【发布时间】:2020-11-27 06:55:52
【问题描述】:

我有这个代码:

document.querySelector('#myfile').onchange = function(e) {
  var files = this.files;
  window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function(fs) {
    let file = files[0];
    let nem_file_name = file.name + '_copy';
    fs.root.getFile(nem_file_name, {
      create: true,
      exclusive: true
    }, function(fileEntry) {
      fileEntry.createWriter(fileWriter => {
        fileWriter.write(file);
      }, () => alert('error 1'));
    }, err => alert('error 2 ' + err));
  }, () => alert('error 3'));
};
<input type="file" id="myfile" ref="myfile" multiple />

当我使用输入控件选择文件时,我想创建文件的副本。我的代码有什么问题?我没有错误,也没有任何反应

【问题讨论】:

  • 我无法重现它静默失败的问题。当我触发该功能时,它提供了一个非常清晰和明显的错误。

标签: javascript fileapi


【解决方案1】:

modern”API 被称为 File System Access,它仍然只是一个提议,但预计会取代以前的和已弃用的 File System API,并且是已经在 Chromium 浏览器中可用。

要使用此 API 写入文件,您首先使用 showSaveFilePicker() 方法请求 FileHandle,然后您可以从该句柄创建写入器并使用该写入器附加数据:

onclick = async (e) => { // needs to be initiated by an user gesture
  const handle = await showSaveFilePicker(); // prompt "Save As"
  const writer = await handle.createWritable(); // request writable stream
  await writer.write( new Blob( [ "some data" ] ) ); // write the Blob directly
  writer.close(); // end writing
};

但是这个 API 仍然受到过度保护,因此很遗憾,它不能像 StackSnippet 或最流行的摆弄服务在此处使用的那样在跨域 iframe 中运行。所以为了进行现场演示,我必须make a plunker你必须在窗口模式下运行

如果您需要自己设置文件名,则需要使用showDirectoryPicker() 请求目录访问权限,然后使用其getFileHandle() 方法从该目录句柄中获取FileHandle。 plnkr

【讨论】:

  • 是否存在至少在 Chrome 浏览器中本地写入文件的任何解决方案?
  • @mystdeim 你读过这个答案了吗?是的,存在这样的解决方案,其中的代码就是这样做的。
  • 我添加窗口。在您的示例中使用 showSaveFilePicker 之前,它可以工作,谢谢!
  • 顺便说一句,我找不到将自定义文件名传递给 showSaveFilePicker 的可能性。
  • @mystdeim ...它也在答案中,检查第二个plnkr
【解决方案2】:

documentation 声明此方法是非标准的,仅在 Chrome 中且已弃用:

即使与文件和目录条目 API 的其余部分相比, requestFileSystem() 特别不标准;只有 Chrome 实现 它,所有其他浏览器制造商都决定他们不会 实施它。它甚至已从提议中删除 规格。请勿使用此方法!

你不应该使用这个。

【讨论】:

  • 其实对我来说没问题
猜你喜欢
  • 1970-01-01
  • 2015-10-11
  • 2021-11-08
  • 1970-01-01
  • 1970-01-01
  • 2017-09-21
  • 2020-06-28
  • 2020-04-24
  • 2022-01-25
相关资源
最近更新 更多