获取本地json或者yaml等文件内容,展示在编辑框

iview框架可以使用upload组件可以传文件,但是无法读取文件内容

目前后台不需要传文件,只需传文件内容以字符串形式,可以使用HTML5中的FileReader对象

<input type="file" class="file" @change="tirggerFile($event)">
<Button @click="readFile">上传</Button>

上传之后

tirggerFile: function (event) {
          //此处校验文件后缀
var file = event.target.files[0] .name; // (利用console.log输出看file文件对象) properties/xml/json/conf/config/data/ini/txt/yaml/yml/cfg var num = file.split('.'); var mun = num[num.length - 1]; console.log(mun) if (mun == 'ini' || mun == 'properties' || mun == 'xml' || mun == 'json' || mun == 'conf' || mun == 'config' || mun == 'data' || mun == 'txt' || mun == 'config' || mun == 'yaml' || mun == 'cfg') { this.readFile(); } else { this.$Notice.error({ title: '请重新点击选择文件传入符合标准的文件', duration: 2 }); } }, readFile() { let self = this; let fileselect = document.querySelector('input[type=file]').files[0]; //找到文件上传的元素 let reader = new FileReader() // console.log(fileselect); if (typeof FileReader === 'undefined') { alert('您的浏览器不支持FileReader接口'); } reader.readAsText(fileselect, 'gb2312') //注意读取中文的是用这个编码,不是utf-8 reader.onload = function () { console.log(reader.result);//文件内容 } },

最后将获取的文件内容赋值到文本编辑框即可

猜你喜欢

转载自www.cnblogs.com/xu-nian-qin/p/11125558.html
今日推荐