gpt4 book ai didi

javascript - HTML5 文件系统初始化

转载 作者:行者123 更新时间:2023-11-28 02:37:31 25 4
gpt4 key购买 nike

我尝试了一个使用 HTML5 文件系统的简单项目,这样我就可以在客户端存储数据。

我的第一次尝试很成功,因为我一开始就用 JavaScript 启动了一切,并在 onclickonkeypress 事件中操作文件(读取文件并将其附加到文本区域或 P;以及写入/修改文件)。

但是,当我在事件之外同时执行此操作时,文件系统的变量为空/未定义,我无法继续该过程。

这是运行良好的代码:

function initFS() {
window.webkitStorageInfo.requestQuota(PERSISTENT,5*1024*1024,
function(grantedBytes) {
window.requestFileSystem(window.TEMPORARY, grantedBytes, function (filesystem)
{
fs = filesystem;
}, errorHandler);
});
}
document.body.onclick=function()
{
alert(fs);
fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) {
}, errorHandler);
}

alert(fs) 生成 DOM FileSystem,这意味着 fs 变量是文件系统。

但是当我这样做时:

function initFS()
{
window.webkitStorageInfo.requestQuota(PERSISTENT,5*1024*1024,function(grantedBytes){
window.requestFileSystem(window.TEMPORARY, grantedBytes, function(filesystem) {
fs = filesystem;
}, errorHandler);
})

}


if (window.requestFileSystem) {
initFS();
}
alert(fs);

alert(fs) 返回 null。有什么办法可以解决这个问题吗?任何解释都会对此有用。我的最后一招是添加一个按钮,这样单击后 fs 肯定会是一个文件系统,但我尽量避免使用这种方法。

最佳答案

这可能是因为 requestQuotarequestFileSystem 函数是异步的。换句话说,alert() 是在 fs 设置之前执行的。

那么..您可以将所有代码放入 requestFileSystem 回调中吗?我不清楚你想要实现什么目标

例如你可以这样做:

function initFS(callback)
{
window.webkitStorageInfo.requestQuota(PERSISTENT,5*1024*1024,function(grantedBytes){
window.requestFileSystem(window.TEMPORARY, grantedBytes, function(filesystem) {
callback(filesystem)
}, errorHandler);
})

}


if (window.requestFileSystem) {
initFS(function (fs) {
alert(fs)
});
}

关于javascript - HTML5 文件系统初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13233665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com