前端axios下载导出文件工具封装

使用示例:

import { fileDownload } from '@/utils/fileDownload'

fileDownload({ url: process.env.VUE_APP_BASE_URL + `/statistic/pageList/export`, method: 'post', data: data })

工具类:

import store from '../store/index'
import {
    getAccessToken
} from '@/utils'
import axios from 'axios'
const token = store.getters.token || getAccessToken()
// 单个文件下载
export const fileDownload = (obj) => {
    let axiosParams = {
        method: obj.method,
        url: process.env.VUE_APP_apipath + obj.url,
        responseType: 'blob',
        headers: {
            'Authorization': `Bearer ${token}`
        }
    }
    if (obj.method && 'POST' === obj.method.toUpperCase()) {
        axiosParams.data = obj.data ? obj.data : {}
    }
    if (obj.method && 'GET' === obj.method.toUpperCase()) {
        axiosParams.params = obj.params ? obj.params : {}
    }
    return axios(axiosParams).then(res => {
        if (res && res.data) {
            const url = window.URL.createObjectURL(
                new Blob([res.data], {
                    type: 'application/octet-stream'
                })
            )
            if (obj.noLink) {
                return url
            }
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            if (res.headers['content-disposition']) {
                console.log(decodeURI(
                    res.headers['content-disposition'].slice(
                        res.headers['content-disposition'].indexOf('=') + 1,
                        res.headers['content-disposition'].indexOf('.')
                    )
                ))
                link.download =
                    decodeURI(
                        res.headers['content-disposition'].slice(
                            res.headers['content-disposition'].indexOf('=') + 1,
                            res.headers['content-disposition'].indexOf('.')
                        )
                    ) +
                    res.headers['content-disposition'].slice(
                        res.headers['content-disposition'].indexOf('.')
                    )
            } else {
                if (obj.fileName) {
                    link.download = obj.fileName
                }
            }

            document.body.appendChild(link)
            link.click()
            window.URL.revokeObjectURL(url)
        }
    })
}

后端返回设置:

前端axios下载导出文件工具封装_第1张图片

前端axios下载导出文件工具封装_第2张图片
前端axios下载导出文件工具封装_第3张图片

你可能感兴趣的:(前端,javascript,开发语言)