【问题标题】:How to Write in file (user directory) using JavaScript?如何使用 JavaScript 写入文件(用户目录)?
【发布时间】:2016-03-19 05:13:04
【问题描述】:

我想使用 html5 和 javascript 或 jquery 从 chrome(所有版本)写入任何文件的 txt。

我尝试过 FileSystem API,我尝试过的代码是:

函数 onFs(fs) { console.log('test'); fs.root.getFile('log.txt', {create: true, Exclusive: true}, 功能(文件条目){ // fileEntry.isFile === true // fileEntry.name == 'log.txt' // fileEntry.fullPath == '/log.txt' fileEntry.getMetaData(函数(md){ console.log(md.modificationTime.toDateString()); }, onError); }, 错误 ); } window.webkitRequestFileSystem(TEMPORARY, 1024*1024 /*1MB*/, onFs);

但不工作。

有没有办法写入文件?

【问题讨论】:

  • 任何错误抛出?它是桌面版 chrome.v13 还是 +?
  • 没有错误但是没有创建文件,即使console.log没有显示任何东西。 Chrome 版本是 45
  • @BhumiShah 是否需要提示用户下载创建的文件?
  • 不,是后台进程,将数据保存到文件夹中存在的文件中。
  • @BhumiShah "将数据保存到文件夹中的文件中" 您是在引用window.requestFileSystemfilesystem: 协议上创建的TEMPORARY 文件系统,还是,对于例如,~/Downloads 用户文件系统目录?

标签: javascript jquery html


【解决方案1】:

我想在用户目录中写入文件

您不能直接将文件写入用户文件系统。

在搜索类似的问题以准确解决问题后,能够在@Iain 在Where does PERSISTENT file system storage store with chrome? 发布的answer 之后在 plnkr 创建的文件内容为$ cat。该文件已写入用户文件系统~/.config/[chrome, chromium] 目录。

使用文件管理器导航到

  ~/.config/[chrome, chromium]/Default/File System

查看目录;包含以下文本的文件是在一个文件夹名称为两位数的文件夹中找到的,然后在另外两个子目录中;具有单个小写字母作为文件夹名称的子目录;在这个子目录中有另一个子目录,有两个数字作为文件夹名称; window.webkitRequestFileSystem 编写的文件有八位数字作为文件名,没有扩展名,但具有正确的"text/plain" MIME 类型;设置为 Blob type 属性。

然后在terminal

  $ cd ~/.config/[chrome, chromium]/Default/File\ System/[three digits]/[lowercase letter]/[two digits]

  $ cat [eight digits]
  Lorem Ipsum

尚未尝试创建.sh 文件并执行它。可能需要将目录放在path 中或将文件移动到现有path 中的文件夹中;为文件设置适当的permissions。可能会在 chrome / chromium 浏览器设置中调整它,但也没有尝试过。

您可能会编写一个命令将/path/to/file 的文件复制或移动到path 的文件夹中,然后执行该文件;或其他方法。


您可以使用a 元素的download 属性允许将createWriter 创建的文件下载到用户文件系统。

The file system is sandboxed

因为文件系统是沙盒的,一个网络应用程序不能访问另一个 应用程序的文件。您也不能读取或写入文件到任意 用户硬盘上的文件夹(例如,我的图片和我的文档) 开车。

另请参阅Definititons

永久存储永久存储是保留在浏览器中的存储,除非用户将其删除或应用程序将其删除。
临时存储 任何网络应用都可以使用临时存储。它是自动的,不需要请求,但浏览器可以 删除存储而不发出警告。


我想在用户目录中写入文件,因为它必须是用户 可以理解。

编辑、更新

您可以使用上述方法。也就是说,使用文件管理器查看文件夹和文件在

中的显示方式
  ~/.config/[chrome, chromium]/Default/File System

  ## do stuff with contents of file written by `window.requestFilesystem`

要查看 chrome / chromium FileSystem 中的文件,您可以导航到 DevTools -> Experiments -> 检查 FileSystem inspectionlog.txt 应列在 Resources 选项卡 FileSystem 中。

也可以使用 URL 导航到地址栏的文件

filesystem:http://run.plnkr.co/temporary/log.txt

应该有内容

Lorem Ipsum

filesystem:http://run.plnkr.co/temporary/

查看临时文件系统根目录下的所有文件和目录

Exploring the FileSystem API

首次启动带有--allow-file-access-from-files 标志的chrome / chromium,请参阅How do I make the Google Chrome flag "--allow-file-access-from-files" permanent?

下一个

window.requestFileSystem  = window.requestFileSystem 
                            || window.webkitRequestFileSystem;

添加错误处理

function errorHandler(e) {
  var msg = '';

  switch (e.message) {
    case FileError.QUOTA_EXCEEDED_ERR:
      msg = 'QUOTA_EXCEEDED_ERR';
      break;
    case FileError.NOT_FOUND_ERR:
      msg = 'NOT_FOUND_ERR';
      break;
    case FileError.SECURITY_ERR:
      msg = 'SECURITY_ERR';
      break;
    case FileError.INVALID_MODIFICATION_ERR:
      msg = 'INVALID_MODIFICATION_ERR';
      break;
    case FileError.INVALID_STATE_ERR:
      msg = 'INVALID_STATE_ERR';
      break;
    default:
      msg = 'Unknown Error';
      break;
  };

  console.log('Error: ' + msg);
}

你应该可以

function writeFile(fs) {

  fs.root.getFile('log.txt', {create: true}, function(fileEntry) {

    // Create a FileWriter object for our FileEntry (log.txt).
    fileEntry.createWriter(function(fileWriter) {

      fileWriter.onwriteend = function(e) {
        console.log('Write completed.');
        // call `readFile` here
        window.requestFileSystem(window.TEMPORARY, 1024*1024, readFile, errorHandler);

      };

      fileWriter.onerror = function(e) {
        console.log('Write failed: ' + e.toString());
      };

      // Create a new Blob and write it to log.txt.
      var blob = new Blob(['Lorem Ipsum'], {type: 'text/plain'});

      fileWriter.write(blob);

    }, errorHandler);

  }, errorHandler);

}

window.requestFileSystem(window.TEMPORARY, 1024*1024, writeFile, errorHandler);

function readFile(fs) {

  fs.root.getFile('log.txt', {}, function(fileEntry) {

    // Get a File object representing the file,
    // then use FileReader to read its contents.
    fileEntry.file(function(file) {
       var reader = new FileReader();

       reader.onloadend = function(e) {
         console.log(e.target.result)
       };

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

  }, errorHandler);

}

plnkrhttp://plnkr.co/edit/EVVNYYUvHiM545T06kMC?p=preview


注意,在 Chrome 38+ 中,还可以使用 new File() 构造函数创建 File 对象;见Chrome: Create file input from blob with Javascript?

不,它是后台进程,将数据保存到存在的文件中 文件夹。

这种方法也不会自动将创建的文件写入用户文件系统中的现有文件夹。

无论采用哪种方法,都需要用户操作才能将文件保存到用户文件系统。这可以使用 a 元素、data URI How to export JavaScript array info to csv (on client side)?iframe 元素 Download File Using Javascript/jQuery 处的 download 属性来实现;这应该提示用户选择保存文件或不保存文件。


另请参阅The FileSaver interfaceFileSaver.js

【讨论】:

  • 此代码控制台记录“未知错误”并且没有生成文件。我已经使用 file://folder/test.html 运行了这段代码。这是正确的吗?
  • @BhumiShah 能够在 file: 协议的 chrome 42 上返回预期结果,并设置了 --allow-file-access-from-files 标志并启用了 localStorage
  • @BhumiShah “我尝试过,但遇到了同样的错误。” 哪个版本的 chrome ?您可以在 Question 中包含 chrome 的启动命令吗?你能创建一个plnkrplnkr.co来演示吗?
  • 我试过版本 39,45,48 和 laumch 命令是 /usr/bin/google-chrome --allow-access-from-files plnkr.co/edit/ETlOjuSsONXqFaWzS6K9?p=info
  • @BhumiShah 启动标志应该是--allow-file-access-from-files
猜你喜欢
  • 2023-02-15
  • 1970-01-01
  • 1970-01-01
  • 2018-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多