javascript - 当用户通过 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'],
},
}],
});
- 但是是否有适用于更多浏览器和旧 Chrome 版本的东西?
解决方案
从 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:…">
解决方法,文件名取自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>
推荐阅读
- java - Hazelcast 客户实时设置个人客户的时间
- elasticsearch - Elasticsearch Query DSL 日期范围问题
- java - 无法导入 Jsonbject,当我这样做时出现错误
- web-services - IIB:SOAPReply 在处理回复消息时遇到错误
- javascript - 谷歌表格 e.values replaceText 基于输入
- html - CSS 图像未居中对齐
- javascript - PHP在更新SQL表之前检查文件是否存在
- android - [Wi-Fi]Android R 无法编辑企业建议网络
- javascript - 承诺错误:非法参数:函数字符串
- javascript - 需要有关画布加载图像的帮助