JS - Download file from URL and show percentage

Viewed 2335

I'm having some problems downloading files with JS. I have files in Firebase storage and I need to download them. I will not use firebase storage download codes.

This file download URL is as below.

https://firebasestorage.googleapis.com/...

What I want is for it to download the download from the browser as soon as I say download. or when I say download, the download will start and I need to show the percentage of the download to the user.

First, I couldn't find anything to start the download in the browser. By browser I mean it starts the download from the downloads section of the browser.

Secondly, I had problems with downloading in the background and displaying the percentage. I tried a few things for this.

  1. There is a library called js-file-downloader. It meets what I want, but when the download starts I can't get the percentage and when the download is finished the file opens in a new window. It should download the file to the device. https://github.com/AleeeKoi/js-file-downloader

    <script src="js/downloader/dist/js-file-downloader.min.js"></script>

function download() {
    var url = "https://firebasestorage.googleapis.com/...";
    new jsFileDownloader({ 
        url: url,
        process: process,
        filename: "a.jpg"
    })
    .then(function () {
      console.log("Successfull");
    })
    .catch(function (error) {
      console.log("ERROR");
    });
}

function process (event) {
    if (!event.lengthComputable) return; 
    var downloadingPercentage = Math.floor(event.loaded / event.total * 100);
    console.log(downloadingPercentage)
  }; 
  1. I am downloading the file using AJAX. The only problem here is that I can't get the download percentage.
    function download() {
    var url = "https://firebasestorage.googleapis.com/...";
    $.ajax({
        url: url,
        method: 'GET',
        xhrFields: {
            responseType: 'blob'
        },
        progress: function(e) {
            if (e.lengthComputable) {
                const completedPercentage = Math.round((e.loaded * 100) / e.total);
                console.log(completedPercentage);
              }
        },
        success: function (data) {
            var a = document.createElement('a');
            var url = window.URL.createObjectURL(data);
            a.href = url;
            a.download = "a.png";
            document.body.append(a);
            a.click();
            a.remove();
            window.URL.revokeObjectURL(url);
        }
    });
}

I would be very happy if you could help me with this subject. Thank you from now. If there is any missing information, I will add it when you tell me.

1 Answers

It gives me the result I want.

    var url = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerFun.mp4";
    
    $.ajax({
        url: url,
        method: 'GET',
        xhrFields: {
            responseType: 'blob'
        },
        xhr: function () {
            var xhr = new window.XMLHttpRequest();
            xhr.addEventListener("progress", function (evt) {
                if(evt.lengthComputable) {
                    var percentComplete = evt.loaded / evt.total;
                    console.log(percentComplete);
                }
            }, false);
            return xhr;
        },
        success: function (data) {
            var a = document.createElement('a');
            var url = window.URL.createObjectURL(data);
            a.href = url;
            a.download = "google.mp4";
            document.body.append(a);
            a.click();
            a.remove();
            window.URL.revokeObjectURL(url);
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

---------- EDIT ----------

The above code was not downloading the .js file. There are probably other issues that I'm not seeing. The code below eliminates these problems and works better.

It won't work here because I didn't enter the URL.

var downloadcontrol = false;

$(document).ready(function () {

$(".download").off("click").on("click", function () {
var filename = ""; // Fill here
var url = ""; //firebase download url fill here
download(filename, url); // Use of
});
    
$(".downloadcancel").off("click").on("click", function () {
downloadcontrol = true;
});
    
});




function download(filename, url) {
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.addEventListener("progress", function (event) {
        if (event.lengthComputable) {
            if (downloadcontrol == true) {
                downloadcontrol = false;
                xhr.abort();
            }

            var percentcomplete = (event.loaded / event.total) * 100;
            $('.downloadbar').css({ 'width': percentcomplete + '%' });
            $('.downloadpercent').text(percentcomplete.toFixed(0) + '%');
        }
    });
    xhr.onload = (event) => {
        var blob = xhr.response;
        var downloaded = document.createElement('a');
        var downloadedurl = window.URL.createObjectURL(blob);
        downloaded.href = downloadedurl;
        downloaded.download = filename;
        document.body.append(downloaded);
        downloaded.click();
        downloaded.remove();
        window.URL.revokeObjectURL(downloadedurl);
    };
    xhr.open('GET', url);
    xhr.send();
}
.download {
width: 45%;
height: 50px;
background-color: white;
border: 2px solid green;
border-radius: 25px;
color: green;
margin-left: calc(5% - 5px);
cursor: pointer;
}

.downloadcancel {
width: 45%;
height: 50px;
background-color: white;
border: 2px solid red;
border-radius: 25px;
color: red;
margin-top:10px;
cursor: pointer;
}

.downloadprogressbar {
margin-top: 50px;
width: 90%;
margin-left: 5%;
border-radius: 10px;
background-color: rgb(243, 243, 243);
}

.downloadbar {
width: 0%;
height: 10px;
border-radius: 10px;
background-color: #1eb300;
}

.downloadpercent {
width: 90%;
margin-left: 5%;
margin-top: 10px;
font-size: 1.5em;
color: rgb(23, 196, 0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="download">DOWNLOAD</button>
<button class="downloadcancel">CANCEL</button>

<div class="downloadprogressbar"><div class="downloadbar"></div></div>
<p class="downloadpercent">0%</p>

Related