版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/j_bleach/article/details/53574789
最近有从本地读取txt文件的需要,奈何网上搜索js读取本地txt,都是新建一个fso对象,即(FileSystemObject)。自己试了半天不好使(后来发现貌似只能在IE上跑)。于是使用H5的fileReader来解决问题。
flieReader 三种状态: FileReader.readyState:0,1,2
fileReader事件处理,6种。
fileReader读取方法,5种。
HTML:
<input type="file" ng-model="my_file" id="my_file" style="display: none;">
<button value="导入" ng-click="myfile()"></button>
JS:
$scope.myfile = function () {
$("#my_file").click();
}
$("#my_file").bind('change', function (source) {
var file = document.getElementById("my_file").files[0];
var reader = new FileReader();
//将文件以文本形式读入页面
reader.readAsText(file, "gb2312");
reader.onload = function (e) {
var fileText = e.target.result.split("\n");
angular.forEach(fileText, function (data, index) {
if (data.length) {
data = data.split(',')
$scope.persons.push(_.zipObject(['position', 'calculate', 'maxCalculate', 'minCalculate'], data));
}
})
$scope.$apply();
}
})
reader.readAsText(file, “gb2312”); 开始没有注明“gb2312”,读取txt之后,文件显示乱码。注明后解决。