前端项目之导入、导出、下载模板

组件封装

<template>
  <div>
    <el-button
      v-if="importUrl"
      type="success"
      @click="importFile"
    >导入</el-button>
    <el-button
      v-if="exportUrl"
      type="success"
      @click="exportFile"
    >导出</el-button>
    <el-dialog
      title="导入 excel 提示"
      :visible.sync="DialogVisible"
      width="30%"
      center
      :close-on-click-modal="false"
    >
      <span>如果没有模版请先下载模版</span>
      <span slot="footer" class="dialog-footer">
        <el-button style="margin-bottom: 15px" @click="download()">
          下载模板
        </el-button>
        <el-upload
          ref="upload"
          type="primary"
          action="#"
          :http-request="beforeUploadAdd"
        >
          <el-button type="primary">继续导入</el-button>
        </el-upload>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getAccessToken } from "@/utils/auth";
import { ImportExcel, ExportExcel } from '@/api/exportAndImport/exportAndImport'

export default {
  props: {
    importUrl: {
      type: String,
      default: ''
    },
    exportUrl: {
      type: String,
      default: ''
    },
    importCode: {
      type: String,
      default: ''
    },
    exportCode: {
      type: String,
      default: ''
    },
    pam: {
      type: Object,
      default: function() {}
    },
    moduleUrl: {
      type: String,
      default: ''
    }
  },
  data: function() {
    return {
      DialogVisible: false,      
      headers: { Authorization: "Bearer " + getAccessToken() }, // 设置上传的请求头部      
      baseUrl: process.env.VUE_APP_BASE_API,
    }
  },
  methods: {
    async beforeUploadAdd(obj) {
      try {
        const fd = new FormData()
        fd.append('file', obj.file)
        const { code, data } = await ImportExcel(this.importUrl, fd)
        if (code === 200 && !data) {
          this.$message({
            type: 'success',
            message: '导入成功!'
          })
          this.$emit('reload')
        } else if (code === 200 && data) {
          this.$message({
            type: 'error',
            message: '导入失败!'
          })
          this.downloadError(data)
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.DialogVisible = false
      }
    },

    downloadError(data) {
      this.DialogVisible = false
      const val = this.baseUrl + `${data}`
      var a = document.createElement('a')
      a.href = val
      a.click()
    },
    // 下载模板
    download() {
      const val = this.baseUrl + `${this.moduleUrl}`
      
      // token下载方式(不带请求头)
      // const token = getAccessToken()
      // this.DialogVisible = false
      // const val = this.baseUrl + `${this.moduleUrl}?token=${token}`
      // var a = document.createElement('a')
      // a.href = val
      // a.download = 'bidModel.xls'
      // a.click()

	//携带请求头下载方式
      fetch(val, {
          method: 'GET',
          // headers: new Headers({
          //   //自己加的头信息全都要转成string
          //   id: xxxx.toString(),
          //   'ACCESS-TOKEN': window.localStorage.getItem('ACCESS-TOKEN') as string,
          // }),
          headers: this.headers
       })
      .then(res => res.blob())
      .then(data => {
        const blobUrl = window.URL.createObjectURL(data);
        this.downloadFile(blobUrl);
      });
    },

    downloadFile(blobUrl) {
      const a = document.createElement('a');
      a.download = 'bidModel.xls';
      a.href = blobUrl;
      a.click();
    },
    async importFile() {
      this.DialogVisible = true
    },
    // 导出所有项目
    async exportFile() {
      try {
        const { code, data } = await ExportExcel(this.exportUrl, this.pam)
        if (code === 200) {
          const dom = document.createElement('a')
          dom.href = this.baseUrl + data
          dom.style.display = 'none'
          document.body.appendChild(dom)
          dom.click()
          dom.parentNode.removeChild(dom)
        }
      } catch (error) {
        console.error(error)
      }
    }
  }
}
// auth.js
// export function getAccessToken() {
//    return localStorage.getItem(AccessTokenKey)
// }
</script>

页面引入

<ExportAndImport
   export-url="导出接口地址"
   import-url="导入接口地址"
   module-url="模板下载接口地址"
   :pam="参数obj"
   @reload="导入后获取列表方法"
 />

你可能感兴趣的:(笔记,前端)