通常js下载文件并修改文件名大部分人认为是不行的,那么今天给大家带来一个可行的方法

首先我们下载文件时使用接口请求的方式

import axios from 'axios'
export const downloadFile = (url, filename) =>
  axios
    .get(url, {
      responseType: 'blob',
    })
    .then((res) => {
      const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) // 构造一个blob对象来处理数据,并设置文件类型
      if (window.navigator.msSaveOrOpenBlob) {
        // 兼容IE10
        navigator.msSaveBlob(blob, filename)
      } else {
        const href = URL.createObjectURL(blob) // 创建新的URL表示指定的blob对象
        const a = document.createElement('a')
        a.style.display = 'none'
        a.href = href // 指定下载链接
        a.download = filename // 指定下载文件名
        a.click()
        URL.revokeObjectURL(a.href) // 释放URL对象
      }
    })

大家可以试试

downloadFile('http://xxx.xx.xx/abc.xlsx', 'test.xlsx')

 

Logo

前往低代码交流专区

更多推荐