读取本地文件的实现
方案一:用 Ajax 请求本地文件
使用该方法读取本地文件时,必须开启本地服务器,并将文件放在服务器目录下。
function readTextFile(fileName){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", fileName, false);
rawFile.onreadystatechange = function(){
if(rawFile.readyState === 4){
if(rawFile.status === 200 || rawFile.status == 0){
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
readTextFile("http://localhost/readFile/text.txt");
不过,该方法,会抛出一个警告:Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.(翻译过来就是:不推荐使用主线程上的同步XMLHttpRequest,因为它会对最终用户体验造成不利影响。)
方案二:用 FileReader 读取本地文件
<body>
<input type="file" id="datafile">
</body>
<script>
function readInputFile(event) {
let file = event.target.files[0];
if (!file) {
return;
}
let reader = new FileReader();
reader.addEventListener('load', event => {
let content = event.target.result;
alert(content);
});
reader.readAsText(file);
}
document.getElementById('datafile').addEventListener('change', readInputFile, false);
</script>