vue2导入

发布时间:2023年12月29日

父页面

<template>
  <div>
    <div>
      <el-button size="small" @click="excelFn">导入</el-button>
    </div>
    <div v-if="ExcelInSure">
      <excelln :names="names" @close="closeFn"></excelln>
    </div>
  </div>
</template>
<script>
import excelln from './excelln.vue'

export default {
  data() {
    return {
      ExcelInSure: false,
      names: '',
      templateDialogVisible: true,
      showProgress: false,
    }
  },
  components: { excelln },

  methods: {
    // 导入
    excelFn() {
      this.ExcelInSure = true
      this.names = 'WorkExecution'
    },
  },
}
</script>

子页面

<template>
  <el-dialog title="导入" :visible.sync="templateDialogVisible" width="50%" :before-close="onCancel">
    <div class="importFile-win">
      <div class="importFile-con">
        <el-upload
          class="upload-demo"
          style="position: relative"
          ref="upload"
          name="file"
          action="#"
          drag
          :http-request="handleFileUpload"
          :headers="curheaderObj"
          :file-list="fileList"
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :before-upload="beforeUpload"
          :before-remove="beforeRemove"
          :auto-upload="false"
          accept=".xls,.xlsx"
          :limit="1"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
        </el-upload>
        <div v-if="this.name !== 'WorkExecution'" class="downLoad-model">
          <a @click="download">点击模板下载</a>
          <span>只能上传xls/xlsx文件,且一次只能选择一个文件</span>
        </div>
        <div class="downLoad-message">{{ downloadMessage }}</div>
        <el-progress v-if="showProgress" type="circle" :percentage="percent" class="progress" />
      </div>
      <div class="dialog-footer">
        <el-button @click="onCancel">关闭</el-button>
        <el-button type="primary" @click="submitUpload" :loading="loadingList.importFile">上传</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import { get, post } from '@/utils/request'
// 下载
export function xiazai() {
  return get('/123', null, { responseType: 'blob' })
}
// 导入
export function daoru(datas, config) {
  return post('/daoru', datas, config).then(res => res)
}
export function daoruapi(data) {
  return get('/456', data, { responseType: 'blob' }).then()
}

export function czyz(data) {
  return post('546', data).then()
}

export default {
  name: 'uploadExcel',
  data() {
    return {
      name: '',
      loadingList: {
        importFile: false,
      },
      templateDialogVisible: true,

      fileList: [],
      curheaderObj: {},
      downloadMessage: '',
      showProgress: false,
      percent: 0,
      dataexcel: this.excelData,
      idRouter: this.routerId,
    }
  },
  props: {
    names: {
      type: String,
      default: '',
    },
    excelData: {
      type: Object,
      default: () => {},
    },
    routerId: {
      type: String,
    },
  },
  watch: {
    excelData(newVlaue) {
      this.dataexcel = newVlaue
    },
    routerId(newVlaue) {
      this.idRouter = newVlaue
    },
  },
  created() {
    this.name = this.names
  },
  methods: {
    // 下载模板
    async download() {
      if (this.names === 'violations') await xiazai()
      if (this.names == 'TemplateImport')
        await daoruapi({ templateId: this.routerId, tableName: this.dataexcel.tableName })
      this.$message.success('下载模板成功')
    },
    handleFileUpload(fileObject) {
      if (this.name == 'WorkExecution') {
        this.showProgress = true
        var formData = new FormData()
        formData.append('file', fileObject.file)
        const Types = {
          WorkExecution: {
            method: czyz,
            fileName: 'xxxxxxxx',
          },
        }

        Types[this.names].method(formData).then(res => {
          fileObject.onSuccess(res)
          if (res.success && res.data) {
            this.downloadFile(res.data, Types[this.names].fileName)
          }
        })
      } else {
        this.showProgress = true
        var formDatas = new FormData()
        formDatas.append('file', fileObject.file)
        formDatas.append('templateTableId', this.dataexcel.id)
        formDatas.append('templateId', this.idRouter)
        // 请求
        const Type = {
          violations: {
            method: daoru,
            fileName: 'xxxx3',
          },
        }

        Type[this.names].method(formDatas).then(res => {
          fileObject.onSuccess(res)
          if (res.success && res.data) {
            this.downloadFile(res.data, Type[this.names].fileName)
          }
        })
      }
    },

    beforeRemove(file, fileList) {
      this.$confirm(`确定移除 ${file.name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消、',
        type: 'warning',
      })
        .then(function () {
          let index = fileList.findIndex(fileItem => fileItem.uid === file.uid)
          fileList.splice(index, 1)
          this.fileList = fileList
          this.$message.success(`删除${file.name}成功!`)
        })
        .catch(function () {})
      // 阻止其内部删除操作
      return false
    },
    // 关闭
    onCancel() {
      this.templateDialogVisible = false
      this.$emit('close', false)
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    //导入文件连接成功
    uploadSuccess(response, file, fileList) {
      if (response.code === 20000 && response.success === true) {
        this.showProgress = false
        if (response.success && response.data) {
          this.$message.success('文件导入完成,请注意查看结果')
          this.downloadMessage = response.message
        }
        if (response.success && !response.data) {
          this.$message.success('文件导入成功')
          // 提交后刷新列表
          this.onCancel()
        }
      }
    },
    downloadFile(response, fileName) {
      let bstr = window.atob(response)
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      var blob = new Blob([u8arr], { type: 'application/vnd.ms-excel' })
      let url = window.URL.createObjectURL(blob)
      let aLink = document.createElement('a')
      aLink.style.display = 'none'
      aLink.href = url
      aLink.setAttribute('download', decodeURI(fileName))
      document.body.appendChild(aLink)
      aLink.click()
      document.body.removeChild(aLink) // 下载完成移除元素
      window.URL.revokeObjectURL(url) // 释放掉blob对象
    },
    uploadError(err, file, fileList) {
      this.showProgress = false
      this.$message.error('上传连接失败!')
      this.downloadMessage = err.message
      this.onCancel()
    },
  },
}
</script>
<style lang="scss">
.importFile-win {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }

  .importFile-con {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-direction: column;

    .upload-demo {
      width: 100%;
      height: 200px;
      display: flex;
      justify-content: center;
      align-items: center;

      .el-upload--text,
      .el-upload-list {
        height: 100%;
        flex: 1;
      }

      .el-upload--text {
        .el-upload-dragger {
          width: auto;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;
        }
      }

      .el-upload-list {
        border: 1px dashed #d0d2d7;
        margin-left: 2px;
      }
    }

    .downLoad-model {
      width: 100%;
      padding: 10px 0;
      color: #0046ff;
      span {
        color: #f59b00;
        margin-left: 5px;
      }
    }

    .downLoad-message {
      width: 100%;
      padding: 10px 0;
      color: #f56c6c;
    }

    .progress {
      position: absolute;
      display: flex;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: #fff;
    }
  }
}
</style>

文章来源:https://blog.csdn.net/weixin_60906876/article/details/135221324
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。