Search code examples
javascriptfiledownloadprompt

Custom download manager javascript


A file sharing website known as mega.com has a feature that creates a custom download manager. When you download a file, it shows a custom progress bar on the website (presumably loading the file to the cache), then creates a download prompt for the cached file. How would this be produced with javascript?


Solution

  • As far as I know, Mega.com uses this inner download manager because they store data on their servers in an encrypted form; encryption and decryption take place in the browser.

    Storage

    You can use IndexedDB to store binary data. Here's a tutorial from Mozilla, explaining how to download an image using AJAX and save it in IndexedDB.

    When you have data stored in IndexedDB you should have opportunity to download it (from internal browser storage). Here you can read, how to create a download prompt.

    Progress bar

    When using XMLHttpRequest, you can get download progress by providing a handler for the progress event.

    var oReq = new XMLHttpRequest();
    
    oReq.addEventListener("progress", updateProgress, false);
    
    [...]
    
    function updateProgress (oEvent) {
      if (oEvent.lengthComputable) {
        var percentComplete = oEvent.loaded / oEvent.total;
        // ...
      } else {
        // Unable to compute progress information since the total size is unknown
      }
    }
    

    Total size of the file would be unavailable if server didn't send Content-Length with headers.

    Full source code and description on MDN.