Vue - axios excel导出

原创
2018/11/01 20:09
阅读数 1.2K

封装 

/**
 * ajax工具类
 * @Author Canaan
 * @Date 2018/6/6.
 */
import axios from 'axios';

const install = function (Vue) {
    const _val = new Vue();
    const AjaxUtil = {
        fromLock: undefined,
        lockError: 'Idea-755a90e2=09253061-faaf-46f5-b8c4-b8c976bf1609',
        // baseURL: '/pay',        // 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL
        // timeout: 1000,          //指定请求超时的毫秒数
        // headers: {'X-Custom-Header': 'foobar'},  //
        // `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject  promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
        // validateStatus: function (status) {
        //     return status >= 200 && status < 300; // 默认的
        // },

        // paramsSerializer 是一个负责 `params` 序列化的函数
        // responseType 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
        // xsrfCookieName    是用作 xsrf token 的值的cookie的名称
        // xsrfHeaderName  是承载 xsrf token 的值的 HTTP 头的名称
        // onDownloadProgress  允许为下载处理进度事件
        // maxContentLength  定义允许的响应内容的最大尺寸
    };

    /**
     * 加锁 - 表单重复提交
     */
    AjaxUtil.tryLock = function () {
        if (AjaxUtil.fromLock) {
            return true;
        }
        AjaxUtil.fromLock = Math.uuid();
        setTimeout(() => {
            AjaxUtil.unLock();
        }, 5000);
        return false;
    };

    /**
     * 解锁 - 表单重复提交
     */
    AjaxUtil.unLock = function () {
        AjaxUtil.fromLock = undefined;
    };

    /**
     * ajax 通用配置
     */
    AjaxUtil.ajax = axios.create({
        baseURL: '/pay',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Authorization': 'Bearer'
        }
        // validateStatus: AjaxUtil.validateStatus
    });
    const CancelToken = axios.CancelToken;
    const source = CancelToken.source();

    /**
     *  添加请求拦截器
     */
    AjaxUtil.ajax.interceptors.request.use(function (config) {
        // 在发送请求之前做些什么
        config.headers.Authorization = 'Bearer ' + localStorage.getItem("accessToken");
        //如果不是get提交。那么就要加锁,防止表单提交
        if (config.method !== 'get') {
            if (AjaxUtil.tryLock()) {
                config.cancelToken = source.token;
                source.cancel(AjaxUtil.lockError)
            }
        }
        return config;
    }, function (error) {
        AjaxUtil.unLock();
        // 对请求错误做些什么
        return Promise.reject(error);
    });

    /**
     * 二进制流处理
     */
    function blobDataHandle(res) {
        let blobType = res.data.type || "";
        //excel文档下载
        if (blobType.indexOf("application/vnd.ms-excel") >= 0) {
            const blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
            let filename = 'excel.xls';
            if (res.headers.filename) {
                filename = decodeURIComponent(res.headers.filename);
            }

            if ('download' in document.createElement('a')) {
                const downloadElement = document.createElement('a');
                let href = '';
                if (window.URL) href = window.URL.createObjectURL(blob);
                else href = window.webkitURL.createObjectURL(blob);
                downloadElement.href = href;
                downloadElement.download = filename;
                document.body.appendChild(downloadElement);
                downloadElement.click();
                if (window.URL) window.URL.revokeObjectURL(href);
                else window.webkitURL.revokeObjectURL(href);
                document.body.removeChild(downloadElement);
            } else {
                navigator.msSaveBlob(blob, filename);
            }
            return;
        }

        throw "示处理的二进制:" + blobType;
    }

    /**
     * 添加响应拦截器
     */
    AjaxUtil.ajax.interceptors.response.use(res => {
        AjaxUtil.unLock();

        //二进制流处理
        if (res.config && res.config.responseType === 'blob') {
            blobDataHandle(res);
            return;
        }

        //get 请求不处理
        if (res.config.method === 'get') {
            return res.data;
        }

        //这里只处理成功的消息
        if (res.data.code === "0" || res.data.code === 0) {
            if (res.data.msg && res.data.msg.length <= 10) {
                _val.$notify({
                    title: res.data.msg,
                    // message: '操作提示',
                    type: 'success'
                });
            } else if (res.data.msg) {
                _val.$notify.success(res.data.msg);
            } else {
                _val.$notify.success('成功???');
            }
        }
        return res.data;
    }, function (error) {
        if (error.response) {
            AjaxUtil.unLock();
            // 请求已发出,但服务器响应的状态码不在 2xx 范围内
            if (error.response.status === 401) {
                _val.$bus.$emit(_val.$env.TOKEN_INVALID);
            } else if (error.response.status === 403) {
                _val.$alert("访问拒绝:" + error.response.data.msg);
            } else {
                _val.$alert("【" + error.response.status + "】请求出错了" + JSON.stringify(error.response.data));
            }
        } else {
            if (AjaxUtil.lockError !== error.message) {
                AjaxUtil.unLock();
                _val.$alert("请求出错了:" + error.message);
            }
        }
        return Promise.reject(error);
    });

    Vue.prototype.$ajax = AjaxUtil.ajax;    //封装后的
    Vue.prototype.$axios = axios;           //原生的
};

export default install;

 

调用

this.$ajax.get('export/excel/tradePayInfo', {
    params: this.searchForm,
    responseType: 'blob',
});

 

服务层代码-设置请求头:

    private void exportExcelSet(String fileName, HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //response.setContentType("application/octet-stream");    //下载用的流
        try {
            response.setHeader("Content-disposition",
                    "attachment;filename=" + new String(fileName.getBytes("utf-8"),
                            "ISO8859-1"));
            response.setHeader("filename", URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new XyPayException(e);
        }
    }

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部