3

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.

loone96
  • 723
  • 2
  • 13
  • 21

2 Answers2

8

change

res.blob()

to

new Blob([res.data])
Yu Miao
  • 437
  • 2
  • 8
4

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);
        })
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400