blob下载指定格式的文件

主要逻辑

handleExportExcel(){
  exportExcel().then(res=>{
    const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' }) //
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.style.display = 'none';
    link.href = url;
    link.setAttribute('download', `花名册列表-${dayjs().format('YYYY-MM-DD')}`)
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link); // 下载完成移除元素
    window.URL.revokeObjectURL(url); // 释放掉blob对象
  })
}

注意点

  • 首先前后端的响应类型应该相同

  • 注意乱码问题

    • 前端在请求接口中axios中设置 responseType:'blob' resopnseType对应值查看http://www.axios-js.com/zh-cn/docs/#axios-create-config
    export function exportExcel(data) { // 导出
      return request({
        url: '/exportExcel',
        method: 'post',
        responseType: 'blob',
        data
      })
    }
    

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章