解决文件下载跨域

102 阅读1分钟
import axios from 'axios'

let url = `${window.location.protocol}//${window.location.host}${file.url.split('.cn')[1]}`
          }
          axios({
            method: 'get',
            url: url,
            responseType: 'blob',
            withCredentials: false
          })
            .then((res) => {
              console.log('下载', res)
              let type = res.data.type
              type = type + ';charset=utf-8'
              const originName = file.name.substring(0, file.name.lastIndexOf('.'))
              const lastName = res.headers['content-disposition'].match(/.+\.([a-z|A-Z]+).*/)[1] // 获取content-disposition
              console.log('截取file.name获取名称', originName)
              console.log('截取后缀名', lastName)

              const b = new Blob([res.data], {
                type
              })
              const href = URL.createObjectURL(b)
              const a = document.createElement('a')
              a.setAttribute('href', href)
              a.setAttribute('download', `${originName}` + `.${lastName}`)
              a.click()
              URL.revokeObjectURL(a.href)
            })
            .catch((err) => {
              console.error('axios({ERR:', err)
            })