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