前端上传文件并且解析(Vue版)

html代码部分 

<input type="file" ref="upload" accept=".txt" class="file" @change="getTxtList" v-show="false"/>
<el-button size="mini" type="primary" @click="uploadTxt" class="mb20">上传文件</el-button>

js 代码部分

  /**
     * 上传txt文件
     */
    uploadTxt() {
      this.$refs.upload.click()
    },
    /**
     * 上传txt文件并解析
     */
    getTxtList(event) {
      let fileSelect = event.target.files[0]//找到文件上传的元素
      let reader = new FileReader()
      if (typeof FileReader === 'undefined') {
        this.$message.error('您的浏览器不支持FileReader接口')
        return
      }
      reader.readAsText(fileSelect, ['gb2312', 'utf-8'])
      const _this = this
      reader.onload = function () {
        _this.$nextTick(() => {
            console.log(reader.result, "reader.result");  //文件内容

      _this.$refs.upload.value = null; //要及时清除掉上传的文件 防止第二次上传同文件无反应
        })
      }
    }
posted @ 2021-10-12 14:37  Binary二进制  阅读(1752)  评论(0)    收藏  举报