axios---根据文件路径转换成Blob类型进行下载

在做下载功能过程中,常常遇到接口跨域的行为,因为权限不能够直接访问而无法实现下载的情况下,可以将文件路径转成文件流下载下来。

下载方法

// 下载
        getDownLoadFile(fileUrl,fileRow){
            return new Promise((resolve, reject) => {
                let obj = {
                    method: 'get',
                    url:fileUrl,
                    responseType: 'blob'
                }
                this.$axios(obj)
                    .then(data => {
                        resolve(data)
                    })
                    .catch(error => {
                    reject(error.toString())
                    })
                }).then(data=>{
                    let fileName = fileUrl.slice(fileUrl.length - 4)
                    download(data.data,fileRow.fileName + fileName);
                })
        },

按钮触发

 <el-button 
                                @click.stop="getDownLoadFile(fileUrl,row)"
                                v-preventReClick
                                style="padding:0 10px"
                                type="text">
                                下载
                            </el-button>

文件流处理方法

/**
 * 文件流转换
 * @param {} data 
 */
export function download(data, titName, type) {
    if (!data) {
        return
    }
    const blob = new Blob([data], { type: type ? type : "application/vnd.ms-excel" })
    const fileName = titName
    if ('download' in document.createElement('a')) { // 非IE下载
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
    } else { // IE10+下载
        navigator.msSaveBlob(blob, fileName)
        navigator.msSaveBlob(blob)
    }
}

 

posted @ 2022-12-20 16:32  巫小婆  阅读(617)  评论(0编辑  收藏  举报