返回base64,前端实现下载功能

实现效果

Snipaste_2024-07-19_08-54-46.png
<template>
    <el-button type="primary" @click="downloadExcel()" >文件下载模板</el-button>
</template>
<script>
export default {
    data() {
     return{}   
    },
    methods:{
      // 1.点击按钮出发文件下载功能,调用后端接口,接收后端返回的bsae64
      downloadExcel(){
        this.$API.TicketManual.ImportTemplateDownLoad().then(res=>{
          // console.log(res);
          const base64Data = res;
          const fileName = '手工票价数据导入模板.xlsx';
          this.downloadBase64File(base64Data, fileName);
        })
      },
       // 2、将后端返回的bsae64转化为blob
      base64toBlob(base64, type = 'application/octet-stream') {
        const bstr = atob(base64); // atob方法是JavaScript的全局函数,用于将Base64编码的字符串解码为原始二进制数据。
        let n = bstr.length;
        const u8arr = new Uint8Array(n); //处理二进制数据;new Uint8Array是 JavaScript 中表示8位无符号整型数组的类型
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n); // charCodeAt() 方法可返回指定位置的字符的 Unicode 编码,返回值是 0 - 65535 之间的整数,表示给定索引处的 UTF-16 代码单元
        }
        return new Blob([u8arr], { type });
        }
      },
      downloadBase64File(base64Data, fileName){
          var blob = this.base64toBlob(base64Data);
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.style.display = 'none';
          a.href = url;
          a.download = fileName;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          URL.revokeObjectURL(url);
      },
      
}
</script>
<style lang="less" scoped>
</style>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容