我有自己的自定义系统,需要创建txt文件,以便在有新订单时打印现金收据。我需要将这些文件本地保存到计算机的特定位置,但有没有一种方法可以在不提示用户选择文件位置的情况下将文件保存到该位置?是否可以创建自己的FileSystemFileHandle类,然后将其作为句柄传递?
$('.save').click(function() {
saveToFile('from website');
});
async function saveToFile(content) {
const opts = {
type: 'save-file',
accepts: [
{
description: 'Text File',
extension: ['txt'],
mimeType: ['text/plain'],
}
]
}
const handle = await window.chooseFileSystemEntries(opts); // don't to that
// create custom FileSystemFileHandle and point to the file location?
const handle = FileSystemFileHandle;
const writable = await handle.createWritable();
await writable.write(content);
await writable.close();
}
使用文件系统访问API无法实现这一点,但具有讽刺意味的是,自动触发下载仍然是<a download>
方法的一部分。
const a = document.createElement('a');
// undefined
a.download = 'example.txt';
// "example.txt"
a.href = URL.createObjectURL(new Blob(['yolo'], {type : 'text/plain'}));
// "blob:https://example.com/8d494f54-499d-4f32-bdb4-ff047e8c60af"
a.click();
// undefined
// Downloads a file `example.txt` to your Downloads folder