【问题标题】:HTML5 - FileAPI - writing filesHTML5 - FileAPI - 写入文件
【发布时间】:2013-10-15 20:05:53
【问题描述】:

我正在使用 JavaScript 和 HTML5 创建应用程序。我需要将数据写入特定文件,因此我想在代码中设置文件路径。这样做没有问题:

function onInitFs(fs) {
    console.log('Opened file system: ' + fs.name);
}
window.webkitRequestFileSystem(window.TEMPORARY, 5 * 1024 * 1024 /* 5MB */, onInitFs, errHandl);

但问题是,它会引发安全错误,因为没有为 exe 文件设置 --allow-file-access-from-files。我不想为所有页面设置它。我只想为我的页面设置它,即我从本地文件系统打开的页面

例如它可以是 index.html:

C:\page\index.html.

有什么办法吗?

我只知道 manifest.json,但这意味着我必须使用通过 Chrome 商店分发我的应用程序。这对我来说是不可接受的,那样我的项目将没有任何意义。

【问题讨论】:

  • 为什么需要写入特定文件?
  • 因为我需要创造……像 Tiddly Wiki。页面应该是可自行编辑的。

标签: javascript html fileapi


【解决方案1】:

FileAPI 的想法是拥有一个虚拟沙盒文件系统,而不是管理 OS 文件系统。您不能编辑用户驱动器中的任意文件,这将是一个巨大的安全漏洞。

您可能想要做的是动态生成页面。如下例所示,首先保存内容 (html),然后加载并添加到页面:

function onInitFs(fs) {
  console.log('Opened file system: ' + fs.name);

  fs.root.getFile(FILE_NAME, {create: true}, function(fileEntry){
    fileEntry.createWriter(function(fw){
      fw.onwriteend = function(e){ console.info('Write completed'); }
      fw.onerror = function(e){ console.log('Error:'+e.toString()); }

      var blobToWrite = new Blob(['<span>test</span>'], {type: 'text/plain'});
      fw.write(blobToWrite);
    }, null);

    console.log(fileEntry.toURL());
  }, null);

    fs.root.getFile(FILE_NAME, {}, function(fileEntry) {

    fileEntry.file(function(file) {
       var reader = new FileReader();

       reader.onloadend = function(e) {
         var someDiv = document.createElement('div');
         someDiv.innerHTML = this.result;
         document.body.appendChild(someDiv);
       };

       reader.readAsText(file);
    }, null);

  }, null);
}

希望有帮助:)

【讨论】:

    猜你喜欢
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    相关资源
    最近更新 更多