a标签模拟下载图片和excel表格

399 阅读1分钟
  1. 直接下载数据流,后端返回一条get请求的url地址
  2. 下载地址url
  3. 微信头像谷歌本页面下载不了,必须跳转页面自行下载。

1.直接下载数据流

export const ExportMemberData = (taskId,status) => {
  return `${API_PATH}/liz-qywechat-admin/authsec/task/group/msg/customers/user/export/${taskId}/${status}`
}
var a = document.createElement('a');
a.style.display = 'none';
a.download = 'download';
a.href = ExportMemberData(id,status);
a.click();

2. 直接下载url

//ExportManageGroupList POST请求
//导出表格
   handleExport = () => {
      const { searchParmas, stop } = this.state
      if (stop) return
      this.setState({
         stop: true
      }, () => {
         ExportManageGroupList(searchParmas).then(res => {
            if (res.code == 100) {
               var a = document.createElement('a');
               a.style.display = 'none';
               a.download = 'download';
               a.href = res.data;
               a.click();
               this.setState({ stop: false })
            } else {
               throw res
            }
         }).catch(req => {
            this.setState({ stop: false })
            message.error(req.msg ? req.msg : '服务器错误,请稍后重试')
         })
      })
   }

3. 跳转下载

downloadQrCode = (record)=>{
    let a = document.createElement('a')
    a.target = '_blank'
    a.href = record.staticUrl + '?d'
    a.click()
}

blob

export const downloadImage = (imgUrl, download) => {
    function toDataURL(url) {
        return fetch(url).then((response) => {
                return response.blob();
            }).then(blob => {
                return URL.createObjectURL(blob);
            });
    }
    (async function() {
            const a = document.createElement("a");
            imgUrl = imgUrl+'?d='+Math.random()
            a.href = await toDataURL(imgUrl);
            a.setAttribute('download', download ? download:'pic.png')
            a.click();
    })()
}