Files
MyReader-Web/src/downloadTextFile.ts
T

29 lines
1.1 KiB
TypeScript
Raw Normal View History

2026-05-16 23:24:55 +08:00
/**
* 当 File System Access「另存为」不可用时(典型:HTTP 公网域名),
* 用浏览器下载代替,避免保存流程完全失败。
*/
export function downloadTextFile(fileName: string, content: string): void {
const safe = fileName.replace(/[/\\<>|:*?"\u0000-\u001f]/g, '_').trim() || '未命名.md'
const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = safe
a.style.display = 'none'
document.body.appendChild(a)
a.click()
a.remove()
URL.revokeObjectURL(url)
}
/** 当前页面不在「安全上下文」时(如 http://域名,非 localhost),FSA 不可用。 */
export function lacksFileSystemAccessContext(): boolean {
return typeof globalThis.isSecureContext === 'boolean' && !globalThis.isSecureContext
}
export function fileNameFromPath(filePath: string | null): string {
if (!filePath) return '未命名.md'
const base = filePath.replace(/\\/g, '/').split('/').pop()?.trim() || '未命名.md'
return base || '未命名.md'
}