axios请求导出数据到excel文件

客户端利用axios自己封装了一个request,文件名为http.js

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 },
            data,
        } = response;
        // console.log(`receive response[${url.replace(baseUrl, ‘‘)}]: ${JSON.stringify(data)}`);
        return data;
    },
    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);
    },

    export: (url, fileName = ‘download.xlsx‘, data = {}) => {
        if (typeof fileName === ‘object‘) {
            data = fileName;
            fileName = ‘download.xlsx‘;
        }

        request({
            method: ‘post‘,
            url,
            data,
            responseType: ‘blob‘,
        })
            .then(res => {
                if (res.type === ‘application/json‘) {
                    console.log(‘文件导出失败: ‘, res);
                    return;
                }

                const href = window.URL.createObjectURL(new Blob([res]));

                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);
            })
            .catch(error => {
                console.log(‘文件导出失败: ‘, error);
            });
    },

    form: (url, data = {}) => {
        const form = document.createElement(‘form‘);
        form.style = ‘display:none;‘;
        form.method = ‘post‘;
        form.action = baseUrl + (url[0] === ‘/‘ ? ‘‘ : ‘/‘) + url;

        const values = JSON.stringify(data);
        if (values !== ‘{}‘) {
            const input = document.createElement(‘input‘);
            input.type = ‘hidden‘;
            input.name = ‘values‘;
            input.value = values;
            form.appendChild(input);
        }

        document.body.append(form);

        form.submit();
        form.remove();
    },

    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;

 另一个jsx中使用:

import React from ‘react‘;
import * as antd from ‘antd‘;
import request from ‘@/common/http‘;

const { Button } = antd;

class Wrapper extends React.Component {
    exportPaidUsers = () => {
        request.export(‘user/exportPaidUsers‘, ‘付费用户列表.xlsx‘);
    };

    // 渲染
    render() {
        return (
            <div>
                <div style={{ marginBottom: 30 }}>
                    <span>
                        <Button type=‘primary‘ onClick={this.exportPaidUsers.bind(this)}>
                            导出所有付费用户
                        </Button>
                    </span>
                </div>
            </div>
        );
    }
}

export default Wrapper;

 服务端php:

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(‘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;
    }

 

完成了!

 

axios请求导出数据到excel文件

上一篇:吊打面试官:Android中高级面试题 -- 终局之战


下一篇:App(4.22)