您的位置:首页 > Web前端 > Vue.js

VUE + ElementUI浏览器本地导入解析文本文件(不上传至服务器)

2019-02-28 15:58 501 查看
版权声明:转载请注明出处 https://blog.csdn.net/HTouying/article/details/88031760

VUE + ElementUI浏览器本地导入解析文本文件内容(不上传至服务器)。

示例代码:

[code]<template>
<div>
<div class="in-file">
<input type="file" @change="inFile" multiple="multiple" accept="*/*" />
</div>
<!-- ElementUI上传 -->
<el-upload
:auto-upload="false"
:on-change="elInFile"
ref="upload"
class="upload-demo"
accept="*/*">
<el-button slot="trigger" size="mini" type="success" plain>选取文件</el-button>
<i slot="tip" class="el-upload__tip el-icon-info">请选取文本文件</i>
</el-upload>
</div>
</template>
<script>
export default {
name: 'importTxt',
data() {
return {
files: null //文件列表
};
},
methods: {
/**
* input-file调用此函数时,默认传入"$event"
* @param e {@link Object}:$event事件对象;
*/
inFile(e) {
this.files = (e.target || e.srcElement).files;  //获取"input-file"的FileList对象
if (!this.files || !this.files.length)
return;
for (let i = 0, len = this.files.length; i < len; i++)
this.read(this.files[i]);
},
/**
* 文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用。
* @param f {@link Object}:当前上传的文件;
* @param fs {@link Array}:当前文件列表;
*/
elInFile(f, fs) {
this.read(f.raw);
},
/**
* 解析
* @param f {@link File}
*/
read(f) {
let rd = new FileReader();
rd.onload = e => {  //this.readAsArrayBuffer函数内,会回调this.onload函数。在这里处理结果
let cont = rd.reading({encode: 'GBK'});
console.log('文件内容:', cont);
};
rd.readAsBinaryString(f);
}
},
beforeCreate() {
/**
* 读取文件(自定义函数)
* @param pms {@link Object}:参数:
*  @param pms.encode {@link String}:编码格式:
* @return {@link String}:文本内容;
*/
FileReader.prototype.reading = function ({encode} = pms) {
let bytes = new Uint8Array(this.result);    //无符号整型数组
let text = new TextDecoder(encode || 'UTF-8').decode(bytes);
return text;
};
/* 重写readAsBinaryString函数 */
FileReader.prototype.readAsBinaryString = function (f) {
if (!this.onload)       //如果this未重写onload函数,则创建一个公共处理方式
this.onload = e => {  //在this.onload函数中,完成公共处理
let rs = this.reading();
console.log(rs);
};
this.readAsArrayBuffer(f);  //内部会回调this.onload方法
};
}
}
</script>
<style scoped>
.in-file {
text-align: center;
}
</style>

注:重写readAsBinaryString函数中的 this.onload 公共处理方法,在methods的read函数中,被重新覆盖。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐