使用element的upload上传文件并导出excel

<template>
  <div>
    <el-upload
      class="upload-demo"
      ref="upload"
      action="api/upload"
      :headers="config"  		//携带token
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :auto-upload="false"
    >
      <el-button slot="trigger" size="large" type="primary">选取文件</el-button>
      <el-button
        style="margin-left: 10px;"
        size="large"
        type="success"
        @click="submitUpload"
        >上传并转化</el-button
      >
    </el-upload>
  </div>
</template>

<script>
let token = JSON.parse(window.sessionStorage.getItem("token"));
export default {
  data() {
    return {
      fileList: [],
      fileName: ""
    };
  },
  computed: {
    config() {
      return { Authorization: token || "" };
    }
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    submitUpload(param) {
      let file = this.$refs.upload.uploadFiles.pop().raw; //这里获取上传的文件对象
      let name = file.name;
      this.fileName = name.slice(0, -4);
      let formData = new FormData();
      formData.append("file", file);
      this.$axios
        .post("http://xxxxx/xxxx/xxxxx", formData, {
          responseType: "blob"
        })
        .then(res => {
          // 转化为blob对象
          let blob = new Blob([res.data], {
            type: "application/octet-stream"
          });
          //文件名
          let filename = `${this.fileName}.xls`;
          // 将blob对象转为一个URL
          var blobURL = window.URL.createObjectURL(blob);
          // 创建一个a标签
          var tempLink = document.createElement("a");
          // 隐藏a标签
          tempLink.style.display = "none";
          // 设置a标签的href属性为blob对象转化的URL
          tempLink.href = blobURL;
          // 给a标签添加下载属性
          tempLink.setAttribute("download", filename);
          if (typeof tempLink.download === "undefined") {
            tempLink.setAttribute("target", "_blank");
          }
          // 将a标签添加到body当中
          document.body.appendChild(tempLink);
          // 启动下载
          tempLink.click();
          // 下载完成移除元素
          document.body.removeChild(tempLink);
          // 释放blob对象
          window.URL.revokeObjectURL(blobURL);
        });
    }
  }
};
</script>

<style scoped>
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值