【问题标题】:edit txt file with javascript or html5使用 javascript 或 html5 编辑 txt 文件
【发布时间】:2015-03-27 06:51:46
【问题描述】:

我需要帮助在客户端编辑 txt 文件,我找不到好的方法。我需要自动更新数据,无需确认,喜欢它:

 <button onclick="updatefile()">Update</button>
   <script>
      functiom updatefile(){
         var file = "d:\test.txt"          
         var data = //here any function for load all data from file
         ...
         ...
         data .= " new data to add";

         //here any function for save data in test.txt  
         .....
      }
</script>

请帮帮我。

【问题讨论】:

  • 您可以使用File Web API 读取本地文件,但无法从浏览器自动保存回文件(出于安全原因)。

标签: javascript html file text-files


【解决方案1】:

您不能使用 JS 以这种方式执行此操作。你可以做的是在客户端下载它,而不需要服务器使用data urls进行干预。

不幸的是,设置所述下载文件的名称不兼容跨浏览器...

HTML

<textarea id="text" placeholder="Type something here and click save"></textarea>
<br>
<a id="save" href="">Save</a>

Javascript

// This defines the data type of our data. application/octet-stream
// makes the browser download the data. Other properties can be added
// while separated by semicolons. After the coma (,) follows the data
var prefix = 'data:application/octet-stream;charset=utf-8;base64,';
$('#text').on('keyup', function(){
  if($(this).val()){
    // Set the URL by appending the base64 form of your text. Keep newlines in mind
    $('#save').attr('href', prefix + btoa($(this).val().replace(/\n/g, '\r\n')));
    // For browsers that support it, you can even set the filename of the 
    // generated 'download'
    $('#save').attr('download', 'text.txt');
  }else{
    $('#save').removeAttr('href');
    $('#save').removeAttr('download');
  }
});

【讨论】:

  • 是否可以选择自定义目录来保存文件?或者文件始终存储在 google chrome 目录中
  • 据我所知,没有办法做到这一点。这取决于浏览器。如果您的应用程序是网络应用程序,您可以将文本临时存储在本地存储中,但您必须通过下载才能真正获取文件。
  • 如果您的应用程序是打包应用程序(如 chrome 扩展程序或独立的 chrome 应用程序),您可能可以将文件保存到沙盒文件系统,但我没有亲自使用过。相关问题:stackoverflow.com/questions/21213397/…
猜你喜欢
  • 2021-10-23
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
  • 2020-05-08
  • 1970-01-01
  • 2016-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多