尽管大家都这么说,您可以通过 javascript 创建客户端文件。这是文件系统的沙盒部分,通过 HTML5 的 FileSystem API 完成。
但是,我的猜测是您的 SECURITY_ERR 可能是因为您在浏览器中通过File://PATH_TO_HTML_PAGE 打开带有目标 javascript 的 html 页面。除非您从服务器获取 html/javascript/css,否则文件系统 API 将不起作用(例如 locahost:8080/test.html - 如果您没有使用服务器的经验,Netbeans 有一些选项可以在您的机器上轻松地在本地运行 glassfish/server 实例.).
2014 年 1 月 31 日更新
在an article on the File-System API 中找到了这个,这对我来说证实了上述段落:
如果您从 file:// 调试应用程序,您可能需要 --allow-file-access-from-files 标志。不使用这些标志将导致 SECURITY_ERR 或 QUOTA_EXCEEDED_ERR FileError。
结束更新
也就是说,在之前对 different question you asked and I answered 的评论中,您使用的是 TEMPORARY 存储。我使用PERSISTENT,因为它更可靠,并且浏览器会显示一条消息,请求允许在目标机器上本地存储数据。以下是过去几年我在客户端计算机上本地制作文件以进行持久数据存储的方式。据我所知,这仅适用于少数浏览器,我使用谷歌浏览器 - 以下内容肯定适用于谷歌浏览器。
以下是 javascript,需要在外部脚本或 script 标签内。
//this is a callback function that gets passed to your request for the file-System.
var onInitFs = function(fileSys){
//fileSystem is a global variable
fileSystem = fileSys;
//once you have access to the fileSystem api, then you can create a file locally
makeAFile();
makeAndWriteContent();
};
var errorHandler = function(e){console.log('Error', e);};
//request 1 GB memory in a quota request
//note the internal callback `function(grantedBytes){...}` which makes the actual
//request for the Filesystem, on success `onInitFs` is called.
///on error the `errorHandler` is called
navigator.webkitPersistentStorage.requestQuota(1024*1024*1024*1, function(grantedBytes) {
window.webkitRequestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler);
}, errorHandler);
//this method will only work once the fileSystem variable has been initialized
function makeAFile(){
var callbackFunctionOnSuccess = function(){console.log("created new file")}
fileSystem.root.getFile("test.txt", {
create: true
}, callbackFunctionOnSuccess, function(error){console.log(error);});
}
function makeAndWriteContent(){
//this is going to be passed as a callback function, to be executed after
//contents are written to the test2.txt file.
var readFile = function(){
fileSystem.root.getFile("test2.txt", {create: false}, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
console.log(this.result);
};
reader.readAsText(file);
}, function(error){console.log(error);});
}, function(error){console.log(error);});
}
fileSystem.root.getFile("test2.txt", {
create: true
}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.onwriteend = function(e) {
writer.onwriteend = function(e){
//now, we will read back what we wrote.
readFile();
}
writer.onerror = function(e3){console.log(e3);
}
var blob = new Blob(["Hello World"]);
writer.write(blob);
};
writer.onerror = function(e3) {console.log(e3);};
//make sure our target file is empty before writing to it.
writer.truncate(0);
}, errorHandler);
}, errorHandler);
}
要记住的一点是,文件系统 API 是异步的,因此您必须习惯使用回调函数。如果您尝试在文件系统 API 实例化之前访问它,或者如果您尝试在文件准备好之前访问它们,您也会收到错误消息。回调函数是必不可少的。