js如何判断是txt文件
在JavaScript中,可以使用以下方法来判断一个文件是否是txt文件:
1.使用文件的扩展名进行判断,txt文件的扩展名为“.txt”
var fileName = "example.txt";
if (fileName.endsWith(".txt")) {
console.log("This is a txt file.");
} else {
console.log("This is not a txt file.");
}
2.读取文件的内容进行判断,如果文件内容是文本格式,则可以认为是txt文件
var file = document.getElementById("file-input").files[0]; // 获取上传的文件
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result; // 获取文件内容
if (/^[\u0000-\u007F]*$/.test(contents)) { // 使用正则表达式判断是否为纯文本
console.log("This is a txt file.");
} else {
console.log("This is not a txt file.");
}
};
reader.readAsText(file); // 读取文件内容
原文地址: https://www.cveoy.top/t/topic/beG4 著作权归作者所有。请勿转载和采集!