[英]save text file with javascript using fileSaver.js and Blob.js
[英]Javascript: Save a text/blob to a file using 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>
提前致谢
请检查一下。
我以这种方式对您的代码进行了修改。
***注意:我导入了FileSaver.js
(从此处下载),并在另一个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");
}
您可以实现以下功能:
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浏览器中对其进行了测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.