如何使用JavaScript写入文件(用户目录)?

时间:2016-03-19 05:13:05

标签: javascript jquery html5

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

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

function onFs(fs) {
 console.log('test');
  fs.root.getFile('log.txt', {create: true, exclusive: true},
      function(fileEntry) {
        // fileEntry.isFile === true
        // fileEntry.name == 'log.txt'
        // fileEntry.fullPath == '/log.txt'

        fileEntry.getMetaData(function(md) {
          console.log(md.modificationTime.toDateString());
        }, onError);

      },
      onError
  );
}

window.webkitRequestFileSystem(TEMPORARY, 1024*1024 /*1MB*/, onFs);

但不行。

有没有办法写入文件?

1 个答案:

答案 0 :(得分:3)

  

我想在用户目录中写文件

您无法直接将文件写入用户文件系统。

在搜索SO以查找类似问题以准确解决问题之后,能够$ catanswer发布@ Where does PERSISTENT file system storage store with chrome?The file system is sandboxedDefinititons创建的文件内容。该文件已写入~/.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中的文件夹,然后执行该文件;或其他方法。

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

  

Exploring the FileSystem API

     

由于文件系统是沙盒,因此Web应用程序无法访问另一个   应用程序的文件。您也无法读取或写入任意文件   用户的文件夹(例如,我的图片和我的文档)很难   驱动。

另见How do I make the Google Chrome flag "--allow-file-access-from-files" permanent?

  

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

  

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

修改,更新

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

中的显示方式
  ~/.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的{​​{1}}标签上。

还可以使用网址

导航到地址栏中的文件
FileSystem

应该有内容

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

Lorem Ipsum

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

请参阅http://plnkr.co/edit/EVVNYYUvHiM545T06kMC?p=preview

首先使用filesystem:http://run.plnkr.co/temporary/ 标记启动chrome / chromium,请参阅Chrome: Create file input from blob with Javascript?

下一步

--allow-file-access-from-files

添加错误处理

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);
}

plnkr How to export JavaScript array info to csv (on client side)?

注意,在Chrome 38+上,也可以使用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); } 构造函数创建File对象;见Download File Using Javascript/jQuery

  

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

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

使用任一方法都需要用户操作将文件保存到用户文件系统。这可以使用new File()元素download The FileSaver interfacea元素FileSaver.js上的data URI属性来实现;这应该提示用户选择保存文件或不保存文件。

另请参阅{{3}},{{3}}