使用AJAX下载文件

使用AJAX下载文件

直接贴代码

download (url, fileName, type) {
    axios({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: {
        'content-disposition': `attachment;filename=${type}`,
        'content-type': 'application/x-download;charset=utf-8'
      }
    })
      .then(res => {
        const blob = new Blob([res.data], {type: type})
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', fileName)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
  }

项目中使用的vue所以用的axios 后台直接返回的文件二进制流

关于参数

  1. url 文件下载url路径
  2. fileName 文件名称
  3. type 文件类型

评论

暂无评论