【封装】 兼容性最强下载文件

/**
 * 兼容性最强下载文件
 * url 接口
 * data 数据
 * method
 */
export const downloadFile = (url, data, method = 'GET') => {
    const body = document.getElementsByTagName('body')[0];
    const form = document.createElement('form'); // <form method='GET' action='https://www.baidu.com'>
    form.method = method;
    form.action = url;
    for (const key of Object.keys(data)) {
        const param = document.createElement('input'); // <input name="startTime" value="2019-07-15" />
        param.type = 'hidden';
        param.name = key;
        param.value = data[key];
        form.appendChild(param);
    }
    body.appendChild(form);
    form.submit(); // 发请求
    body.removeChild(form);
    // </form> => submit() => 发送请求 url ?{startTime: '2019-07-15'} => 返回响应 文件流,浏览器自动下载
};

二、 使用

1)Angular中使用

    downloadLogApi(taskId: string) {
        downloadFile(`${API_PREFIX}/jira/tasks/${taskId}/log/download`, {}, 'GET');
        return void 0;
    }

2)vue当中使用

// 导出 预约人员信息列表 {直播id, 平台id}
export const requestExportLiveUserList = ({liveId, platformId}) => {
    const url = preFixed + '/live/exportOrderLiveUserList';

    const reqBody = emptyCannotRequest({
        liveId,
        platformId
    });
    downloadFile(url, reqBody, 'GET');
    return 0;
};
原文地址:https://www.cnblogs.com/mailyuan/p/13815160.html