How does the Mega.co.nz download progress-bar work

downloadmega

The Question is in the title: How does the Mega.co.nz download progress-bar work? I know about the filesystem API, but how are the files streamed from the server to the filesystem? How do they get the progress of the download?

Best Answer

Calculating the % of bytes already downloaded is an easy task once you have in hands the total bytes already download and the total filesize. The file transfer may occur in any method, such as websockets or XMLHttpRequest (Mega uses this last one), but the main point is: it's totally useless to create a file download system exactly like Mega unless you want to keep encrypted files on your server (it's the case of Mega).

Once Mega downloads reaches 99%, it shows "decrypting...". This means that the whole file is sent encrypted. As the decryption key on the URL is after a "#", it suggests that the decryption key is not sent to the server and stays on the client-side.

Mega uses FileSystem API to go storing the encrypted file somewhere on your %APPDATA% (I've heard that they store the encrypted file as blob using browser storage APIs if the browser does not support FileSystem API). Once all the bytes are transferred, the file decryption algorithm runs also on your browser (with Javascript), takes the file content and decrypts it without the need of the server. Finally, it (hiddenly) creates a object URL for the blob and forces your browser to download it (you can achieve it with FileSaver).