四时宝库

程序员的知识宝库

vue上传txt文件,并且读取txt内容

本文转载于https://blog.csdn.net/weixin_37817251/article/details/95657541

需求:点击上传txt文件,先读取txt文件中的内容进行展示。

上传使用的是element的upload如下:

 
<el-upload action="/"
    ref="upload"
    accept=".txt"			                      
    :before-upload="beforeUpload"
    :disabled="this.fileList.length !== 0"			                         
    :default-file-list="this.fileList">
<el-button type="primary" :disabled="this.fileList.length !== 0">上传文件</el-button>
</el-upload>
 

下面是业务逻辑:

beforeCreate() {
    // 读取文件
    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方法
    };
},
methods:{
  beforeUpload(file){
    this.fileList = [file]
    console.log('选择了文件beforeUpload')
    // 读取数据
    this.read(file);
    return false
  },
    read(f) {
      let rd = new FileReader();
      rd.onload = e => {  
        //this.readAsArrayBuffer函数内,会回调this.onload函数。在这里处理结果
        let cont = rd.reading({encode: 'GBK'});
        console.log(cont);
        let  formerData = this.textData;
        this.textData = formerData + "\n" + cont;
      };
      rd.readAsBinaryString(f);
    }
}

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接