js 上傳文件獲取數據,下載生成json文件

<template>
      <input type="file" name="file" id="uploadData" style="display:none" @change="uploadChange"/>
      <el-button @click="operationBtn('upload')">上傳</el-button>
      <el-button @click="operationBtn('download')">下載</el-button>
</template>

 

const arrow = {} // 標繪

methods:{
    operationBtn(type) {
      if (type === 'upload') { // 上傳
        const upload = document.querySelector('#uploadData');
        upload.click();
      } else if (type === 'download') { // 下載
        const data = arrow.saveData(); // 獲取標繪數據
        if (!data) return this.$Message.warning('保存的數據爲空!');
        this.saveJSON(data);
      }
    },
    uploadChange(e) { // document.querySelector('#uploadData')
      if (!e.target.value) {
        this.$message.error('內容不能爲空!');
      }
      // console.log(e.target.files[0].size); // 文件字節數
      const { files } = e.target;// 獲取到文件列表
      if (files.length === 0) {
        this.$message.error('請選擇文件');
      } else {
        const reader = new FileReader();
        reader.readAsText(files[0], 'UTF-8');// 讀取文件
        reader.onload = function (evt) { // 讀取完文件之後會回來這裏
          const fileData = JSON.parse(evt.target.result || '{}'); // 讀取文件內容
          arrow.showData(fileData);// 顯示標繪
        };
      }
    },
    saveJSON(data, filename) { // 生成json文件
      if (!filename) { filename = '標繪.json'; }
      if (typeof data === 'object') {
        data = JSON.stringify(data, undefined, 4);
      }
      const blob = new Blob([data], { type: 'text/json' });
      const e = document.createEvent('MouseEvents');
      const a = document.createElement('a');
      a.download = filename;
      a.href = window.URL.createObjectURL(blob);
      a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
      e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
      a.dispatchEvent(e);
    },
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章