Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'blob' does not exist on type 'AxiosResponse<any>'

I've been working on file download link with React/Typescript project and got into this problem.

     axios({
            method: "post",
            url: "http://localhost:8080/test",
            data: bodyFormData,
            headers: { "Content-Type": "multipart/form-data" },
            responseType: 'blob',
        })
            .then(res => res.blob())
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                // the filename you want
                a.download = 'test.xml';
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                alert('your file has downloaded!')
            }).catch(function (e) {
                //handle error
                console.log(e);
            })

reference: Download a file by jQuery.Ajax

When I try this, Typescript claims an error. I also try to change res.blob() to res.data.blob() then it doesn't claim an error but browser console says blob() is not a function.

like image 494
loone96 Avatar asked Oct 20 '25 15:10

loone96


2 Answers

change

res.blob()

to

new Blob([res.data])
like image 92
Yu Miao Avatar answered Oct 23 '25 04:10

Yu Miao


With axios you do not need to use res.blob() since you already provide the contentType headers. You caan directly use the response data

 axios({
        method: "post",
        url: "http://localhost:8080/test",
        data: bodyFormData,
        headers: { "Content-Type": "multipart/form-data" },
        responseType: 'blob',
    })
        .then(res => { 
            const blob = res.data
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            // the filename you want
            a.download = 'test.xml';
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            alert('your file has downloaded!')
        }).catch(function (e) {
            //handle error
            console.log(e);
        })
like image 30
Shubham Khatri Avatar answered Oct 23 '25 04:10

Shubham Khatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!