Web前端接收后端接口的二进制文件流(二进制数据流)

239 阅读1分钟

第一步:在请求接口时设置返回的文件类型

responseType:'blob'

export function getQrcode(path) {
    return request({
    url: '/mall/pagedevise/getCode?path=' + path,
    method: 'get',
    responseType: 'blob' // 返回文件的类型
    })
}

第二步:返回中调用解析二进制方法

createQrcode(row) {
    const path = '/pagesA/pages/activityPage/index?clientType=' + row.clientType;
    getQrcode(path).then((res) => {
        isExcel('jpg', dateFormats(Date.now()), res.data);
    });
},

解析导出的二进制文件流

type: 文件的类型

name: 文件名称

data: 接口返回的二进制流

export const isExcel = (type, name, data) => {
    const link = document.createElement('a');
    const blob = new Blob([data]);
    link.style.display = 'none';
    link.href = URL.createObjectURL(blob);
    link.setAttribute('download', `${name}.` + type);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
};