首页 > 解决方案 > 如何在 React js 中下载一种流文件?

问题描述

我想在我的项目中下载一个流文件。实际上,API 的响应形式就像一个 blob。我在这里留下我的代码;

idfilterBody作为我的组件的道具到达。

如果有些地方有错误或没有,我真的很困惑吗?谁能帮我找出我的错误?谢谢你。

const fetchBlobFile = async (setBlobFile, id, filterBody) => {
    try {
        let response = await get(`http://localhost:4000/error/table/export?error_id=${id}`, filterBody)
        setBlobFile(response?.data?.blob())
    } catch (error) {
    }
}

function exportXslFile ({id, filterBody}) {
    const [blobFile, setBlobFile] = useState(null)

useEffect(() => {
        fetchBlobFile(setBlobFile, id, filterBody)
    }, [id])

    const export = () => {
        const url = window.URL.createObjectURL(blobFile);
        window.location = url
    }
return (
<button className="export" onClick={export}><ExportXslFile /> Export</button>
)

}


标签: reactjsdownloadblob

解决方案


我解决了以下问题。此代码完全有效;但只注意导入必要的包。

const fetchBlobFile = async (setBlobFileLoading, id, body) => {
    try {
        const a = document.createElement("a");
        a.style.display = "none";
        document.body.appendChild(a);
        setBlobFileLoading(true);
        var data = JSON.stringify(body);

        var config = {
            method: 'post',
            url: `http://localhost:4000/table/export?errorCsv_id=${id}`,
            headers: {
                'Content-Type': 'application/json'
            },
            data: data
        };

        let response = await axios(config);
        setBlobFileLoading(false)
        const blobFile = new Blob([response?.data], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blobFile);
        a.href = url;
        a.download = fileName; 
        a.click();
        window.URL.revokeObjectURL(url);
    } catch (error) {

    }
}

function exportXslFile ({id, body}) {

const [blobFileLoading, setBlobFileLoading] = useState(false)


    const export = () => {
fetchBlobFile(setBlobFileLoading, id, filterBody)
    }
return (
{blobFileLoading && <div className="loading fixed"><Loader /></div>} // set up loader
<button className="export" onClick={export}>Export</button> 
) //download button

}

推荐阅读