前端导入和读取文本文件

<template>

  <div>

    <el-input v-model="fileName" style="width:50%" />

    <input ref="file" style="display: none" type="file" accept=".json" @change="handleClick">

    <el-button style="width: 20%; margin-left:10px" type="primary" @click="openFolderDialog">浏览</el-button>

    <el-button style="width: 20%" type="primary" @click="importFile">导入</el-button>

  </div>

</template>

<script>

export default {

  data() {

    return {

      fileName: '',

      fileContent: ''

    }

  },

  mounted() {

  },

  methods: {

    openFolderDialog() {

      this.$refs.file.click()

    },

    handleClick(e) {

      const files = e.target.files

      const fileobj = files[0]

      this.fileName = fileobj.name

      var reader = new FileReader()

      reader.readAsText(fileobj, 'utf-8')

      const vm = this

      reader.onload = function() {

        // console.log('文件时:', reader.result)

        vm.fileContent = JSON.parse(reader.result)

      }

    },

    importFile() {

      console.log(this.fileContent)

    }

  }

}

</script>

<style>

</style>

猜你喜欢

转载自blog.csdn.net/zheng_chang_wei/article/details/104607769