axios下载excel文件

html下载文件

最简单的方式莫过于使用a标签赋予href下载,或者是window.open,但是却无法执行post请求、以及在request.headers中放置内容,以下提供一种方式,基于axios

import axios from 'axios'

axios.interceptors.response.use(
    response => {
        if(response.config && response.config.responseType == 'blob') {
            const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' }); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
            let filename = 'excel.xls';
            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;

        }
        return Promise.resolve(response.data);
        /* const { status, config } = response;
        const { onlyHandleSuccess } = config;
        if(!onlyHandleSuccess) return Promise.resolve(response.data);
        else {
            const { success, data, errorCode, errorMsg } = response.data;
            if(success) return Promise.resolve(data);
            else ElementUI.Message.error(errorMsg);
        } */

        /* if(status >= 200 && status < 300) {
            return Promise.resolve(data);
        }
        return Promise.reject(response); */
    },
    error => {
        const { response } = error;
        let message = '异常', status;
        if(!response) message = '请求超时...';
        else {
            message = response.statusText;
            status = response.status;
        }
        return Promise.reject({ message, status });
    }
)

const defaultConfig = {
    baseURL: '',
    mode: 'cors',    
    headers: {
        "your-content": 'test....',
        "Accept": "application/json",   
        "Content-Type": "application/json;charset=utf-8"
    }, 
    responseType: 'json'
    //onlyHandleSuccess: true
}

axios.defaults.timeout = 30000

export const post = (url, data, config) => {
    return axios.post(url, data, Object.assign({}, defaultConfig, config))
}

//demo,请求地址需要返回文件流
post('your/download/path', { data: 1 }, { responseType: 'blob' });
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013224660/article/details/79981350
上一篇在macOS的浏览器上使用灰阶渲染字体,修复字体过粗的问题
下一篇nginx处理跨域
想对作者说点什么? 我来说一句

axios离线文件

2017年09月12日 12KB 下载

没有更多推荐了,返回首页

关闭
关闭