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
      })
    }
    

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