我在博文 html5读取本地文本文件及图片文件 介绍了一些例子
https://blog.csdn.net/cnds123/article/details/120469779
下面介绍在本地保存文本的例子,源码如下:
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>在本地保存文本</title> <script > function download(){ var text = document.getElementById("my-textarea").value; var blob = new Blob([text], { type: "text/plain"}); var anchor = document.createElement("a"); anchor.download = "my-filename.txt"; anchor.href = window.URL.createObjectURL(blob); anchor.target ="_blank"; anchor.style.display = "none"; // just to be safe! document.body.appendChild(anchor); anchor.click(); document.body.removeChild(anchor); } </script> </head> <body> <textarea id="my-textarea" rows="15" cols="60"> 在这里输入文本... </textarea> <br> <button type="button" onclick="download()">Save</button> </body> </html>
运行效果如下:
下面介绍在本地读入和保存文本的例子,源码如下
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>在本地读入和保存文本</title> </head> <body> <script> var ff function show() { var reader = new FileReader(); reader.onload = function() { //alert(this.result) story.value=this.result } var f = document.getElementById("filePicker").files[0]; ff=f.name; //alert(f.name) reader.readAsText(f); } function download(){ var text = document.getElementById("story").value; var blob = new Blob([text], { type: "text/plain"}); var anchor = document.createElement("a"); //anchor.download = "my-filename.txt"; anchor.download = ff; anchor.href = window.URL.createObjectURL(blob); anchor.target ="_blank"; anchor.style.display = "none"; // just to be safe! document.body.appendChild(anchor); anchor.click(); document.body.removeChild(anchor); } </script> <input type="file" name="file" id="filePicker" onchange="show()" /> <br> <textarea id="story" name="story" rows="15" cols="60"> </textarea> <br> <button type="button" onclick="download()">downloadSave</button> </body> </html>
运行效果如下:
进一步学习可参考:
将HTML5 textarea内容保存到文件 - VoidCC
使用HTML5 / JavaScript生成并保存文件_CHCH998的博客-CSDN博客_html5 保存文件