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);
    },
}

 

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