[英]How can I prevent the File System Access API from saving file when an error occurs?
When saving a file using the File System Access API, if an error occurs between writing to and saving a new file, a file is still created and saved.使用文件系统访问 API 保存文件时,如果在写入和保存新文件之间发生错误,仍会创建并保存文件。
Is there a way to prevent this file from being created and saved?有没有办法防止这个文件被创建和保存?
As an example using the following code, an error is thrown before the save function is ran.作为使用以下代码的示例,在运行保存函数之前抛出错误。 This error prevents the save function from running;
此错误会阻止保存功能运行; however, a file is still created.
但是,仍然会创建一个文件。
let fileHandle; async function save() { let stream = await fileHandle.createWritable(); await stream.write(); await stream.close(); } async function saveFile() { const options = { types: [{ description: 'Text File', accept: { 'text/plain': '.txt' }, }], excludeAcceptAllOption: true, } try { fileHandle = await window.showSaveFilePicker(options); } catch (err) { return; } throw "Some error occurs, preventing the 'save' function from being reached..."; save(); }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>File System Access Test</title> <script type="text/javascript" src="test.js"></script> </head> <body> <button type="button" onclick="saveFile()">Save File</button> </body> </html>
all preventions can be created through validations所有预防措施都可以通过验证来创建
For example create a class that validates the parameters that you require to be fulfilled and if the validation is correct then execute the save function.例如,创建一个类来验证您需要满足的参数,如果验证正确,则执行保存功能。
Your code is already working, I only moved the last lines because they are unnecessary.您的代码已经在运行,我只移动了最后几行,因为它们是不必要的。
I tested your code creating a folder that cannot create files inside我测试了您的代码,创建了一个无法在其中创建文件的文件夹
async function saveFile() {
const options = {
types: [{
description: 'Text File',
accept: {
'text/plain': '.txt'
},
}],
excludeAcceptAllOption: true,
}
// here i make the changes
try {
fileHandle = await window.showSaveFilePicker(options);
save();
} catch (err) {
alert('failed')
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.