javascript - 使用javascript或html5编辑txt文件

标签 javascript html file text-files

请帮助我在客户端编辑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>

请帮助我。

最佳答案

你不能使用 JS 以这种方式做到这一点。不过,您可以做的是在客户端上下载它,而无需使用数据网址让服务器进行干预。

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

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

关于javascript - 使用javascript或html5编辑txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29267736/

相关文章:

php - 如何实现mysql事件的历史记录?

java - 将用于将 Assets 文件复制到 Android 中的缓存文件夹的 Java 代码转换为 Kotlin 的最佳实践

javascript - setState 意外更新非状态属性

html - 如何制作边框覆盖子div?

javascript - 如何将 Angular 对象传递给 pug mixin?

javascript - 为什么 Lightbox 会扩展我的网页?

c# - 在 .NET 中获取文件类型

c - 如何清空 Char 数组并在 C 中重复使用?

java - PopupPanel Glass z-index 1 总是在最前面?

javascript - isalpha 替代 JavaScript?