vue+axios实现文件下载

import axios from 'axios'
/**
 * 入库纠正和数据库数据页面的导出方法
 */
export function exportListData(bookings,url) {
  if(bookings.length>0){
    axios.post(url,{
        ids:bookings,  //传参
      },{
        headers:{'Content-Type':'application/json'}
      }
    ).then((response) => {
      if(response.status == 200){
        const content = response.data
        const blob = new Blob([content])
        let fileName = ''
        if(response.headers['content-disposition'].split(';').length>0){
          fileName =response.headers['content-disposition'].split(';')[1].split("=")[1]
        }else{
          fileName = 'data.csv'
        }
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      }
    }).catch((error) =>{
      console.log('失败');
    });
  }else{
    alert('暂无数据')
  }

后台接口需要配置Access-Control-Expose-Headers: Content-Disposition,前端才能通过response.headers['content-disposition']获取到放在header中的文件名

你可能感兴趣的:(vue,文件下载)