如何读取上传的txt文件的内容及其存在的问题

625 阅读1分钟

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

一、如何读取文件内容

需求是读取 test.txt 文件中的版本信息,并在页面上显示。

1、test.txt 内容

version:1.1.0
啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊
aaaaaaaaaaaaaaaaaaaaa
2333333333333333333333
gfhgjhgkk,j.kllj.jlkjddsaeqwedwweds

2、html

<template>
  <div>
    <el-upload
      class="upload-demo"
      action="#"
      :on-change="handleChange"
      :auto-upload="false"
      :file-list="file_list"
      style="margin-bottom: 20px"
    >
      <el-button size="small" type="primary">上传</el-button>
    </el-upload>
    
    <div>版本:{{file_version}}</div>
  </div>
</template>

3、js

<script>
export default {
  data() {
    return {
      file_list:[],
      file_content:[],
      file_version:''
    };
  },
  methods:{
    handleChange(file){
      const reader = new FileReader()// 读取文件内容
      reader.readAsText(file.raw, 'utf-8') // 防止中文乱码问题,不加reader.onload方法都不会触发
      reader.onload = () => {
        this.file_content = reader.result.split('\r\n')// txt文本内容,接下来就可以对其进行校验处理了
        console.log("insideFileContent:" + this.file_content)
      }
      console.log("outFileContent:" + this.file_content)
      this.file_content.forEach((item)=>{
        if(item.indexOf('version') > -1){
          this.file_version = item
        }
      })
      console.log("version:" + this.file_version)
    }
  }
};
</script>

4、输出结果

image.png

二、问题及解决办法

1、存在的问题

根据结果分析,在 reader.onload 函数的外部无法获取函数内部的数据,这种情况跟 promise 是不是很像,所以用promise来解决,除此之外可以在  reader.onload 函数的内部直接使用数据。

2、解决办法

内部使用

handleChange(file){
      const reader = new FileReader()// 读取文件内容
      reader.readAsText(file.raw, 'utf-8') // 防止中文乱码问题,不加reader.onload方法都不会触发
      reader.onload = () => {
        var file_content = reader.result.split('\r\n')// txt文本内容,接下来就可以对其进行校验处理了
        console.log(file_content)

        file_content.forEach((item)=>{
        if(item.indexOf('version') > -1){
          this.file_version = item
        }
      })
      console.log("version:" + this.file_version)
    }
}

image.png

promise

handleChange(file) {
      new Promise(function (resolve) {
        const reader = new FileReader(); // 读取文件内容
        reader.readAsText(file.raw, "utf-8"); // 防止中文乱码问题,不加reader.onload方法都不会触发
        reader.onload = () => {
          // txt文本内容,接下来就可以对其进行校验处理了
          resolve(reader.result.split("\r\n"));
        };
      }).then((file_content) => {
        console.log(file_content)
        file_content.forEach((item) => {
          if (item.indexOf("version") > -1) {
            this.file_version = item;
          }
        });
        console.log("version:" + this.file_version);
      });
    },

image.png