前端get方式下载文件

一般下载方式都是用get去请求,通过动态创建a标签的形式去完成下载,给a标签设置download属性。

并且要声明传递blob格式 

responseType: 'blob',

 getHeader()为我设置请求头信息的方法

import CryptoJS from 'crypto-js'   

    getHeader(apiUrl) {
        this.jurisdiction = window.sessionStorage.getItem('jurisdiction').split(',')
        this.authType = window.sessionStorage.getItem('user.authType');
        let token = window.sessionStorage.getItem('zx.token');
        let api = apiUrl;
        let version = '1.0.0';
        let device = 'web';
        let timestamp = new Date().getTime();
        let secretKey = CryptoJS.HmacSHA1(device + '\n' + timestamp + '\n' + version, api).toString();
        let accessToken = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse((token == null ? '' : token) + ':' + secretKey));
        return this.request_head = {
          'Authorization-Device': device,
          'Authorization-Version': version,
          'Authorization-Timestamp': timestamp,
          'Authorization': accessToken,
        }
      },
      downLoad() {
      
        this.$ajax.get("/user/selectUsersPrint", {
          headers: this.getHeader('/user/selectUsersPrint'),
          responseType: 'blob',
          params: {}
        }).then(response => {
          let url = window.URL.createObjectURL(new Blob([response.data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', '用户数据' + filtersTime.filters.yearMonthTime(new Date()) + '.xls')
          document.body.appendChild(link)
          link.click()
        }, response => {
          console.log("获取信息失败");
          console.log(response);
        })
      }

 

    原文作者:Dreamer_xr
    原文地址: https://blog.csdn.net/xr510002594/article/details/90905462
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞