Mosen
Mosen

Reputation: 75

How to download a kind of stream file in React js?

I would like to download a stream file in my project. Indeed the response form the API is like a blob. Here i leave my code;

id and filterBody arrives as props to my component.

Really i confused if some where there are mistakes or No? Can any one help me to find my mistakes? Thank you.

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>
)

}


Upvotes: 0

Views: 11258

Answers (1)

Mosen
Mosen

Reputation: 75

I solved the problem as following. This code completely works; but only be careful to import necessary packages.

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

}

Upvotes: 3

Related Questions