前端文件下载常用的几种方式

40 阅读1分钟

axios使用json下载文件流

  • 定义:可以传递json。不适用于已有封装全局请求的axios
  • 使用注意点:
    1. 声明responseType:'blob'.
    2. 使用Blob接收
    3. 动态文件名content-disposition接收。雷点:某些浏览器不会暴露该头部字段,需要服务器允许跨域访问该头部
axios({
      headers: {
        // 'hero-platform-code': type
      },
      url: 'https://localhost/download/test',
      method: 'post',
      data: {
        "headers": [
            "姓名",
            "年龄",
            "城市"
        ],
        "data": [
            {
                "姓名": "张三",
                "年龄": 25,
                "城市": "北京"
            },
        ],
        "fileName": "99"
    },
      responseType: 'blob',
      withCredentials: true
    }).then(response => {
      console.log(response, 'response')
      // 从响应头中获取文件名
      const disposition = response.headers['content-disposition']
      let filename = 'aa.xlsx' // 默认文件名
      if (disposition && disposition.indexOf('filename=') !== -1) {
        // 从Content-Disposition中提取文件名
        filename = disposition.split('filename=')[1].replace(/"/g, '')
        // 解码文件名(处理中文)
        filename = decodeURIComponent(filename)
      }
      const blob = new Blob([response.data], { type: response.headers['content-type'] })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = filename
      document.body.appendChild(link)
      link.click()
      window.URL.revokeObjectURL(url)
    })

axios使用formData下载文件流

  • 定义:类似于form提交下载
  • 使用注意点:
    1. 声明Content-Type:'application/x-www-form-urlencoded'.
    2. 创建FormData传递参数
    3. 动态文件名content-disposition接收。参考json下载
var formData = new FormData();
formData.append("key","value")
axios({
      headers:{
      'Content-Type': 'application/x-www-form-urlencoded',
      },
      url: 'http://localhost/api/download' ,
      method: 'post',
      data: formData,
      responseType: 'blob',
      withCredentials: true
    }).then(response =>{
      console.log(response,'response')
      const blob = new Blob([response.data], { type: response.headers['content-type'] })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = '游戏管理.xlsx'
      document.body.appendChild(link)
      link.click()
      window.URL.revokeObjectURL(url)
      })

form方式下载文件流

  • 定义:form提交下载
  • 使用注意点:
    1. 声明Content-Type:'application/x-www-form-urlencoded'.
    2. 创建FormData传递参数
    3. 动态文件名content-disposition接收。参考json下载
  const paraData = { id: 1212, name: '测试名' }
  console.log(paraData)
  var form = document.createElement('form')
  form.style.display = 'none'
  form.action = gateUrl + '/api/dictData/downloadDictDataList'
  form.method = 'post'
  document.body.appendChild(form)
  for (var key in paraData) {
    if (paraData[key]) {
      var input = document.createElement('input')
      input.type = 'hidden'
      input.name = key
      input.value = paraData[key]
      form.appendChild(input)
    }
  }

  form.submit()
  form.remove()