原创

前端js下载文件

温馨提示:
本文最后更新于 2022年09月14日,已超过 581 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

js下载文件(这里使用的是axios来请求的)

axios文档

import axios from 'axios'
或是let axios = require('axios')

/**
 * @private
 * @param {Blob} blob
 * @description 解析返回的信息,如果没能解析成json那说明是二进制数据流,解析成json通常就是后端报错了
 */
const transferBlobToJson = (blob) => {
    return new Promise(((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = function() {
            try {
                const res = JSON.parse(reader.result);
                resolve(res)
            } catch (e) {
                reject(e)
            }
        }
        reader.readAsText(blob)
    }))
}
/**
 *
 * @param {string} url 文件链接
 * @param {string} fileName 文件名称
 * @param { string } method 请求方法
 * @param data 请求参数
 * @description 下载二进制文件
 */
export const downloadBlob = ({ url, fileName, method = 'GET', data = {} }) => {
    return axios({
        url,
        method,
        data,
        responseType: 'blob',
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(async (res) => {
            let success = true
            try {
                const jsonRes = await transferBlobToJson(res)
                if (jsonRes.status && jsonRes.status !== 200) { // 导出失败时返回的json
                    success = false;
                    res = jsonRes;
                }
            } catch (e) {
            }
            if (!success) throw res;
            let downUrl = URL.createObjectURL(res)
            let anchor = document.createElement('a')
            anchor.href = downUrl
            anchor.download = fileName
            anchor.click()
            window.URL.revokeObjectURL(downUrl)
        })
}
正文到此结束