你瞅啥呢

2025-02-20 前端下载后端返回的二进制流

    fetch('接口地址', {
        method: 'GET', // 请求方法
    })
    .then(response => {
        if (!response.ok) {
               console.log(`HTTP error! Status: ${response.status}`);
        }
        return response.blob(); // 将响应数据解析为 Blob
    })
    .then(blob => {
        // 创建一个临时的 URL 对象
        const url = window.URL.createObjectURL(blob);
        // 创建一个 <a> 元素用于下载
        const link = document.createElement('a');
        link.href = url;
        link.download = 'hello-world.txt'; // 设置下载文件名
        // 将 <a> 元素添加到 DOM 中
        document.body.appendChild(link);
        // 模拟点击触发下载
        link.click();
        // 清理临时对象和元素
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
    })
    .catch(error => {
        console.error("error", error);
    });

 

posted @ 2025-02-20 23:49  叶乘风  阅读(24)  评论(0)    收藏  举报