用 blob 下载 excel 文件

axios设置 responseType: 'blob'

大概是这样:

axios({
    method: 'get', 
    url: url, // 接口地址
    responseType: 'blob'
})

如果在拦截器里设置,这样写:

instance.interceptors.request.use(
    config => {
        if (options.isDownloadFile) {
            config.responseType = 'blob'
        }
})
let option = {
    jonId: 1
}
let fileName = '作业1'
download(option, fileName)

function download(option, fileName){
    //  request 函数是用 axios 封装的请求组件
    return request({
        url: '/api/job/export',
        data: option,
        needCamelCase: false,
        isDownloadFile: true,
        needLoading: true
    }).then((data) => {
        fileName = (fileName || '导出作业').trim()
        saveFile(data, fileName + '.xlsx')
    })
}

function saveFile(data, fileName) {
    let file = data
    let url = window.URL || window.webkitURL;
    let fileURL = url.createObjectURL(file);
    let a = document.createElement("a");
    a.href = fileURL;
    a.download = fileName;
    a.target = "_self";
    a.click();
    url.revokeObjectURL(fileURL);
}

你可能感兴趣的:(用 blob 下载 excel 文件)