工具函数:下载文件

93 阅读1分钟
/**
 * @description: 下载文件
 * @param {String} 文件下载地址
 * @param {String} 文件名字,要带后缀
 */
export function downLoadFile(filepath, fileName) {
  return new Promise((resolve, reject) => {
    fetch(filepath)
      .then(res => res.blob())
      .then(blob => {
        const a = document.createElement('a')
        document.body.appendChild(a)
        a.style.display = 'none'
        const url = window.URL.createObjectURL(blob)
        a.href = url
        a.download = fileName
        a.click()
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url)
        resolve()
      })
      .catch(err => {
        reject(new Error(err))
      })
  })
}