使用JavaScript创建文本文件并下载

1,082 阅读2分钟

使用JavaScript创建文本文件并下载

如果您希望您的代码能够动态生成文本(如JSON)文件并由用户的浏览器下载,可以学习一下这个案例。

index.js

 /**
  * @fileoverview 提供文本(如JSON),使用JavaScript创建文件并下载文件
  * @author AcWrong
  * @param {string} textTowrite 
  * @param {string} fileNameToSaveAs 
  * @param {string} fileType 
  */
 function saveTextAsFile(textTowrite, fileNameToSaveAs, fileType) {
     //提供文本和文件类型用于创建一个Blob对象
     let textFileAsBlob = new Blob([textTowrite], { type: fileType });
     //创建一个 a 元素
     let downloadLink = document.createElement('a');
     //指定下载过程中显示的文件名
     downloadLink.download = fileNameToSaveAs;
     downloadLink.innerHTML = 'Download File';
 ​
 ​
     downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
     downloadLink.style.display = 'none';
     document.body.appendChild(downloadLink);
 ​
     //模式鼠标左键单击事件
     downloadLink.click();
 }

功能非常简单:它以要写入的文本、要保存的文件名和文件类型作为参数。然后,它使用给定的文本和文件类型创建一个新的Blob对象。之后,它创建一个新的a元素,并将下载属性设置为给定的文件名。

然后使用URL.createObjectURL()方法为Blob对象创建URL。然后,它将元素的href属性设置为上面创建的URL。之后,它将a元素附加到body元素并单击它。

因此,如果您想使用JavaScript创建和下载文本文件,可以使用上面的函数。例如,如果您想创建并下载一个名为hello.txt、内容为hello World!的文本文件!,你可以这样做:

 saveTextAsFile('Hello World!', 'hello.txt', 'text/plain');

同样,如果你想创建并下载一个名为hello.JSON、内容为{“hello”:“world”}的JSON文件,你可以这样做:

 saveTextAsFile('{"hello": "world"}', 'hello.json', 'application/json');

index.html

 <!DOCTYPE html>
 <html lang="en">
 ​
 <head>
     <meta charset="UTF-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Create and download text files using JavaScript</title>
     <script src="./index.js"></script>
     <link rel="stylesheet" href="./style.css">
 </head>
 ​
 <body>
     <div class="container">
         <button onclick="saveTextAsFile('Hello World!','hello-world.txt')" class="downloadBtn">Download file</button>
     </div>
 </body>
 ​
 </html>

style.css

 .container {
     font-family: sans-serif;
     background-color: #3c3c3c;
     display: flex;
     align-items: center;
     justify-content: center;
     height: 100vh;
     flex-direction: column;
 }
 ​
 .downloadBtn {
     display: flex;
     background: linear-gradient(135deg, #7932f6, #805ad5 48%, #342662);
     color: white;
     padding: 6px 22px;
     margin: 8px 0;
     border-radius: 7px;
     cursor: pointer;
     font-size: 18pt;
     border: none;
     box-shadow: 0 2px 2px 0 rgb(0 40 56 / 15%);
     font-weight: bold;
     transition: box-shadow 300ms ease-in;
     text-decoration: none;
 }