文件下载

// 区分ie浏览器和chrome浏览器实现修改文件名
function downloadFile(url, fileName, encode, suffix, noHomologous) {
  let urlPathload = url
  if (encode) {
    const tmpFileName = url.split('/').pop()
    const urlPath = url.split(tmpFileName)[0]
    urlPathload = urlPath + encodeURIComponent(tmpFileName)
    console.log(tmpFileName, urlPath, urlPathload)
  }
  if (noHomologous) {
    console.log('noHomologous');
    let link = document.createElement('a')
    link.href = `${url}` // a标签下载同源策略
    link.download = fileName
    link.click()
  } else if (url.indexOf('http://') >= 0) {
    let link = document.createElement('a'),
      href = url.replace('http://', 'https://')
    link.href = `${href}?response-content-type=application/octet-stream` // a标签下载同源策略
    link.download = fileName
    link.click()
  } else {
    console.log(suffix, 'axios');
    axios({
      method: 'get',
      url: encode ? urlPathload : url,
      // data:  encryptList.Encrypt(JSON.stringify(params)),
      // data: params,
      responseType: 'blob',
      // headers: {
      //   'token': tool.getToken(),
      //   appId: 36,
      //   'Content-Type': 'application/x-www-form-urlencoded'
      // }
    }).then(res => {
      const link = document.createElement('a')
      const blob = new Blob([res.data], {
        type: suffix || 'application/vnd.ms-excel'
      })
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob)
      link.setAttribute('download', `${fileName}`)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link);
    }).catch(err => {
      console.log('导出报错', err);
    });
  }
}

 

posted @ 2022-09-01 10:26  张小中  阅读(30)  评论(0编辑  收藏  举报