Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REACT: download a file with Axios using a progress bar

Tags:

reactjs

axios

I have an application that downloads a zip file in this way. It works regularly but when clicked, the download is performed in the background and the browser shows the actual download of the file only when the whole stream has been downloaded locally. So if the file takes 1 minute to download, the user doesn't understand what the site is doing. Is there any way to show a progress bar?

await axios({
      url: sUrl,
      method: "GET",
      responseType: "blob" // important
    })
      .then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", fname); //or any other extension
        document.body.appendChild(link);
        link.click();
        this.setState({ downloading: false });
      })
      .catch(error => {
        this.setState({ downloading: false });
        message.warn("Errore: " + error.message);
        return [];
      });
like image 475
Luca F. Avatar asked Dec 07 '25 10:12

Luca F.


1 Answers

Yes, you can achieve this by using onDownloadProgress method provided by axios package, check the below example :

await axios({
    url: sUrl,
    method: "GET",
    responseType: "blob", // important
    onDownloadProgress: (progressEvent) => {
        let percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total); // you can use this to show user percentage of file downloaded
    }
})
like image 183
Abhay Sehgal Avatar answered Dec 09 '25 00:12

Abhay Sehgal



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!