关于前端:用-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);
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理