axios请求导出数据到excel文件(二)
上一篇的文章存在一定的问题, 没有把export接口做成Promise, 所以无法在那个接口完成后继续作一些事, 而且不支持取服务端中设定的文件名, 所以这次的更新做个优化, 解决这些问题!
客户端http.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | import axios from 'axios' ; import history from './history' ; export const baseUrl = '/api' ; const request = axios; // or axios.create({}) request.defaults.baseURL = baseUrl; request.interceptors.request.use(config => { // const { url, data } = config; // console.log(`send request[${url}]: ${JSON.stringify(data)}`); return config; }); request.interceptors.response.use( response => { const { // config: { url }, headers, data, } = response; if (headers[ 'content-type' ].indexOf( 'application/json' ) >= 0) { if (data instanceof Blob) return response; else return data; } else { return response; } }, error => { console.log(`receive response[${ 'url' }]: ${JSON.stringify(error)}`); return Promise.reject( error && error.response && error.response.data && error.response.data.message ? error.response.data.message : error, ); }, ); const method = { get: (url, data = {}) => { return request.get(url, { params: data }); }, post: (url, data = {}) => { return request.post(url, data); }, // 导出数据到excel文件 export : (url, data = {}, fileName = '' ) => { return new Promise((resolve, reject) => { if ( typeof data === 'string' ) { fileName = data; // 第2个参数是文件名 data = {}; } request({ method: 'post' , url, data, responseType: 'blob' , }) .then(res => { const data = res.data; if (data.type === 'application/json' ) { const reader = new FileReader(); reader.onload = function () { try { const json = JSON.parse( this .result); reject(json); } catch (err) { console.log( 'fail: ' , err); reject(err); } }; reader.onerror = function (error) { reject(error); }; reader.readAsText(data); return ; } // 导出数据到文件 if (fileName === '' ) { fileName = res.headers[ 'content-disposition' ] .split( ';' )[1] .split( 'filename=' )[1] .replace(/"/g, '' ); fileName = decodeURIComponent(fileName); } const href = window.URL.createObjectURL( new Blob([data])); const link = document.createElement( 'a' ); link.style.display = 'none' ; link.href = href; link.setAttribute( 'download' , fileName); document.body.appendChild(link); link.click(); document.body.removeChild(link); window.URL.revokeObjectURL(href); resolve(); }) . catch (error => { console.log( '文件导出失败: ' , error); reject(error); }); }); }, all: (...https) => { return new Promise((resolve, reject) => { request .all(https) .then( axios.spread((...resList) => { // 多个请求都发送完毕,拿到返回的数据 resolve(resList); }), ) . catch (err => { reject(err); }); }); }, }; export const http = (url, data, success, fail) => { return new Promise((resolve, reject) => { method .post(url, data) .then(res => { const { code } = res; if (code === 101) { history.replace( '/' ); history.fail && fail(); reject(); } if (code === 100 || code === 102) { history.replace( '/login' ); fail && fail(); reject(); } else { success && success(res); resolve(res); } }) . catch (error => { fail && fail(error); reject(error); }); }); }; export default method; |
调用示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | import React from 'react' ; import * as antd from 'antd' ; import request from '@/common/http' ; const { Button, message } = antd; class Wrapper extends React.Component { exportPaidUsers = () => { request . export ( 'user/exportPaidUsers' ) // .export('user/exportPaidUsers', '付费用户列表.xlsx') .then(() => { message.info( '文件导出成功' ); }) . catch (err => { message.warn(err.msg); }); }; // 渲染 render() { return ( <div> <div style={{ marginBottom: 30 }}> <span> <Button type= 'primary' onClick={ this .exportPaidUsers.bind( this )}> 导出所有付费用户 </Button> </span> </div> </div> ); } } export default Wrapper; |
服务端php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public static function download(PHPExcel $excel , String $fileName = 'download' ) { $ua = strtolower ( $_SERVER [ 'HTTP_USER_AGENT' ]); if (preg_match( '/msie/i' , $ua ) || preg_match( '/edge/i' , $ua ) || preg_match( '/trident/i' , $ua ) ) { $fileName = urlencode( $fileName ); } ob_end_clean(); header( 'Content-Type: application/vnd.ms-excel;charset=utf-8' ); // header(sprintf('Content-Disposition: attachment;filename="%s.xlsx"', $fileName)); header(sprintf( 'Content-Disposition: attachment;filename="%s.xlsx"' , urlencode( $fileName ))); // 编码下,解决中文乱码问题(客户端需要解码) header( 'Cache-Control: max-age=0' ); $ta [] = microtime(true); $writer = \PHPExcel_IOFactory::createWriter( $excel , 'Excel2007' ); $writer ->save( 'php://output' ); $ta [] = microtime(true); log_message2( 'download: ' , $ta ); exit ; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)