首页 > 解决方案 > 当用户通过 showSaveFilePicker 保存 blob 时建议文件名

问题描述

不确定这是否是愚蠢的要求,但在网上找不到任何东西:

我网站上的用户可以将文件保存到他们的磁盘:

const saveFile = async blob => {
    try {
      const handle = await window.showSaveFilePicker({
        types: [
          {
            description: "Mp3 file",
            accept: { "audio/mp3": [".mp3"] },
          },
        ],
      })
      const writable = await handle.createWritable()
      await writable.write(blob)
      await writable.close()
      return handle
    } catch (err) {
      console.error(err.name, err.message)
    }
  }

如您所见,此文件不在任何服务器上,而是来自 blob。它工作正常,但我想建议一个比 simple 更好的文件名Untitled.mp3,这样理想情况下用户只需要按回车键而不必担心命名文件(但如果她愿意,可以这样做) .

这可能吗?

我在看这个这个,但找不到任何有用的东西!

我知道在 Chrome 91 中我可以做到:

const handle = await self.showSaveFilePicker({
  suggestedName: 'song.mp3',
  types: [{
    description: 'Mp3 file',
    accept: {
      'audio/mp3': ['.mp3'],
    },
  }],
});

标签: javascriptdomsaveclient-sidefile-system-access-api

解决方案


从 Chrome 91 开始,您可以使用suggestedName,如我们的文章中所述。不幸的是,91 之前的 Chrome 版本不支持此参数。

const fileHandle = await self.showSaveFilePicker({
  suggestedName: 'Untitled Text.txt',
  types: [{
    description: 'Text documents',
    accept: {
      'text/plain': ['.txt'],
    },
  }],
});

备选方案 1

对于<a download="suggested_name.txt" href="blob:…&quot;>解决方法,文件名取自download属性的值,如文档中所述。

备选方案 2

如果您想(或可以)涉及服务器,则可以使用Content-Disposition标头,如MDN中所述。

200 OK
Content-Type: text/html; charset=utf-8
Content-Disposition: attachment; filename="cool.html"
Content-Length: 21

<HTML>Save me!</HTML>


推荐阅读