文件的上传利用input标签的type="file"属性,读取用FileReader对象,下载通过创建a标签实现

<template>
  <div class="filediv">
    <el-button @click="downloadFile">下载</el-button>
    <div id="fileselect">
      <el-input style="margin-top: 16px" type="file"></el-input>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
    }
  },
  mounted: function () {
    this.$nextTick(function () {
      this.readFile()
    })
  },
  methods: {
    // 下载文件
    downloadFile: function () {
      var content = [
        { 'firstName': 'John', 'lastName': 'Doe' },
        { 'firstName': 'Anna', 'lastName': 'Smith' },
        { 'firstName': 'Peter', 'lastName': 'Jones' }
      ]
      var filecontent = JSON.stringify(content)
      if ('download' in document.createElement('a')) {
        this.download(filecontent, 'testfile.json')
      } else {
        alert('浏览器不支持')
      }
    },
    // 下载设备配置文件
    download: function (content, filename) {
      let link = document.createElement('a')
      link.download = filename
      link.style.display = 'none'
      // 字符内容转变成blob地址
      let blob = new Blob([content])
      link.href = URL.createObjectURL(blob)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    // 导入设备,监听上传文件并读取
    readFile: function () {
      console.log('读取文件')
      let fileselect = document.querySelector('#fileselect')
      fileselect.addEventListener('change', function (e) {
        console.log(e)
        let file = e.target.files
        console.log('文件类型')
        console.log(file)
        if (file.length === 0) {
          return
        }
        let reader = new FileReader()
        if (typeof FileReader === 'undefined') {
          this.$message({
            type: 'info',
            message: '您的浏览器不支持FileReader接口'
          })
          return
        }
        reader.readAsText(file[0])
        reader.onload = function (e) {
          console.log('文件内容')
          console.log(e.target.result)
        }
      }.bind(this))
    }
  }
}
</script>

<style scoped>
.filediv {
  width: 400px;
  margin: 20px;
}
</style>

 

Logo

前往低代码交流专区

更多推荐