使用 new Blob() 將文本框數據保存為 txt文件


<textarea name="" id="text" cols="40" rows="10">
  第一行:這里輸入的數據將保存為txt中
  第二行:保存為文件
</textarea>
<button id="save" type="button">保存</button>
<script>
  document.querySelector("#save").addEventListener("click", saveFile);
  function saveFile() {
    var inValue = document.querySelector("#text").value;
    var blob = new Blob([inValue], { type: "text/plain;charset=utf-8" });
    const fileName = "test.txt";
    console.log("msSaveOorOpenBlob" in navigator)
    if ("msSaveOorOpenBlob" in navigator) {
      //IE 瀏覽器
      window.navigator.msSaveOorOpenBlob(blob, fileName);
    } else {
      //不是IE瀏覽器
      var url = window.URL.createObjectURL(blob);
      var link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", fileName);
      link.click();
    }
  }
</script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM