要获取文件的内容,您需要使用输入标签选择文件。
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input id="input" type="file" accept="text/plain">
<script src="script.js"></script>
</body>
读取文件内容的好时机是在change事件中。
const input = document.querySelector("#input");
input.addEventListener("change",() => {
const file = input.files.item(0);
});
要将文件的内容作为字符串读取,您需要将其转换。
function fileToText(file, callback) {
const reader = new FileReader();
reader.readAsText(file);
reader.onload =() => {
callback(reader.result);
};
}
作为字符串的文件内容将可用于回调函数。您可以创建链接并使用click事件将字符串下载到文本文件中。
function save(content, fileName, mime) {
const blob = new Blob([content], {
tipe: mime
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = fileName;
a.click();
}
下面是完整的代码
const input = document.querySelector("#input");
input.addEventListener("change",() => {
const file = input.files.item(0);
fileToText(file, (text) => {
save(text, "fileName.txt", "text/plain");
});
});
function fileToText(file, callback) {
const reader = new FileReader();
reader.readAsText(file);
reader.onload =() => {
callback(reader.result);
};
}
function save(content, fileName, mime) {
const blob = new Blob([content], {
tipe: mime
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = fileName;
a.click();
}
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input id="input" type="file" accept="text/plain">
<script src="script.js"></script>
</body>
您可以在此处详细了解在JavaScript处理文件:https://www.html5rocks.com/en/tutorials/file/dndfiles/
的
可能重复[如何读取和写入文件使用JavaScript](http://stackoverflow.com/questions/585234/how-to-read-and-write-into-file-using-javascript) – Chase 2013-04-25 12:22:53
我在问题标题,说明和提供的代码中看不到任何重要的关系。请尝试在浏览器中使用JS或服务器开发的本机应用程序来解释您的问题的上下文,例如您试图在何处执行此代码。 – saurav 2016-10-14 16:50:13