REACT: download a file with Axios using a progress bar

Viewed 5682

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 [];
      });
2 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
    }
})

Axios package has both onDownloadProgress and onUploadProgress to show a progress bar during download or upload, have you tried them?

I recommend you to have a quick look at this Tutorial

Related