vue 项目中 base64格式文件下载

在这里插入图片描述
其中 this.info 是里包含后端返回的base64文件
数据结构如图
在这里插入图片描述

<template>
  <div>
    <el-dialog
      :title="title"
      width="40%"
      :visible.sync="visible"
      :before-close="onClose"
      :close-on-click-modal="false"
      v-on="$listeners"
    >

      <el-alert
        :title="info.msg"
        type="warning"

        :closable="false"
      />

      <p>
        <el-button
          size="small"
          type="text"

          :loading="loading"
          @click.stop="downloadFun"
        >下载文件</el-button>

      </p>

      <div slot="footer" class="dialog-footer">
        <el-button @click="onClose">取消</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script>

export default {
  props: {
    visible: {
      type: Boolean,
      default: true
    },
    info: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      title: '',
      loading: false
    }
  },
  mounted() {
    // console.log(this.info, 'info')
    this.title = this.info.extra.fileName
  },
  methods: {
    onClose() {
      this.$emit('update:visible', false)
    },
    downloadFun() {
      this.loading = true

      const blob = this.dataURLtoBlob(this.info.extra.fileStream)
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob)
      link.setAttribute('download', this.info.extra.fileName)
      document.body.appendChild(link)
      link.click()

      this.loading = false
    },
    dataURLtoBlob(base64Str) {
      var bstr = atob(base64Str); var n = bstr.length; var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      // 下载的是excel格式的文件
      return new Blob([u8arr], { type: 'application/vnd.ms-excel' })
    }

  }
}
</script>

<style lang="scss" scoped>

</style>

Logo

前往低代码交流专区

更多推荐