1. 程式人生 > >vue中實現檔案的上傳讀取及下載

vue中實現檔案的上傳讀取及下載

檔案的上傳利用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>