Javascript:使用FileSaver.js将文本/斑点保存到文件中

时间:2019-07-29 10:15:35

标签: javascript html button filesaver.js

我建立了2个按钮,

我要将答案保存在文件中:(当然取决于最终用户将按下的按钮)

我已经使用了Javascript对象 blob ,但无法正常工作:

  

未生成文件 testfile1.txt

我在主文件夹中有一个名为 js 的子文件夹,其中有文件 FileSaver.js

因此,我有:

`src="js/FileSaver.js"` 

在我的代码中实现。在我的代码下面:

<!doctype html>
<html lang="en">
<head>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 <script src="js/FileSaver.js"></script>
</head>

<body>
<button id="save-btn"> yes </button>
<button id="save-btn1"> no </button>
<script>
$("save-btn").click(function{

var blob= new Blob(["yes"],
{type:"text/plain;charset=utf-8"}
);
saveAs(blob,"testfile1.txt");
});
$("save-btn1").click(function{

var blob= new Blob(["no"],
{type:"text/plain;charset=utf-8"}
);
saveAs(blob,"testfile1.txt");
});
</script>

</body>
</html>

预先感谢

2 个答案:

答案 0 :(得分:2)

请检查一下。

我以这种方式对您的代码进行了修改。

***注意:我导入了FileSaver.js (downloaded from here)并将按钮单击功能写入了另一个js文件(test.js)

这是我的代码,每次单击“是”或“否”按钮时,都可以使用该代码下载带有输入数据的文本文件。

  

test.html

<head>
<body>
    <button type="button" id="yesButton" value="Yes" onclick="saveYesInputDatataToFile();">Yes</button>
    <button type="button" id="noButton" value="No" onclick="saveNoInputDataToile();">No</button>
    <script src="test.js"></script>
    <script src="FileSaver.js"></script>
</body>
</head>
  

test.js

function saveYesInputDatataToFile() {
    var userInput = document.getElementById("yesButton").value;
    var blob = new Blob([userInput],
    { type: "text/plain;charset=utf-8" });
    saveAs(blob, "userInput.txt");
}

function saveNoInputDataToile() {
    var userInput = document.getElementById("noButton").value;
    var blob = new Blob([userInput],
    { type: "text/plain;charset=utf-8" });
    saveAs(blob, "userInput.txt");
}

答案 1 :(得分:0)

您可以实现以下功能:

let content = 'abc';
const url = window.URL.createObjectURL(new Blob([content], {type: 'text/plain'}));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'log.txt'); //or any other extension
document.body.appendChild(link);
link.click();

我已经在Chrome浏览器中对其进行了测试。