Progress-bar to DOWNLOAD files in Jquery

Asked

Viewed 850 times

5

I have seen many people looking for how to make a progress bar to download files, Megaupload style.

I beat myself up to get here and I’d like to share with the guys!
'Cause I didn’t find anything on the Internet I spent days researching...

  • 3

    Israel is commendable for its good intention in sharing the solution, but the functioning of the OS is different from forums. Could you separate the question from the answer? This way, both stay as the site requires. Take a look at [tour] to see how it should look.

  • 3

    @Israel, as Diego said, in order for its post to be suitable for the site, lacked a small step, but it’s simple. Just [Dit] the question, leaving only doubt, and post the solution in the bottom field, answers.

  • Show! I’ll do it...

1 answer

1

Answer originally included by the author as part of the question

Until I added codes here, there, and I did it!

Follows the code:

function downloadFile(opcoes){
    var options = $.extend({
        typeSend:"GET",
        file:null,
        newfile:null,
        abort:function(e){},
        error:function(e){},
        load:function(e){},
        finish:function(e){},
        progress:function(e){}
    }, opcoes);
    if(options.file==null){
        alert("Por favor, dê um nome ao arquivo...");return false
    }
    $.ajax({
      xhr: function() {
            var xhr = new window.XMLHttpRequest();
            xhr.responseType = "arraybuffer";
            xhr.addEventListener("abort", function() {options.abort()})
            xhr.addEventListener("error", function() {options.error()})
            xhr.addEventListener("loadend", function() {options.finish()})
            xhr.addEventListener("load", function() {
                var file_type = xhr.getResponseHeader('Content-Type');
                var disposition = xhr.getResponseHeader('Content-Disposition');
                if (disposition && disposition.indexOf('attachment') !== -1) {
                    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                }else{
                    filename = options.file.replace(/^.*[\\\/]/, '')
                }
                window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
                window.URL = window.URL || window.webkitURL;
                var arrayBufferView = new Uint8Array( this.response );
                var blob = new Blob( [ arrayBufferView ], { type: file_type } );
                var urlCreator = window.URL || window.BlobBuilder;
                var imageUrl = urlCreator.createObjectURL(blob);
                var a = document.createElement("a");
                document.body.appendChild(a);
                a.href = imageUrl;
                if(options.newfile!=null){
                    a.download = options.newfile;
                }else{
                    a.download = filename;
                }
                a.click(); 
                options.load()

            }, false);
            xhr.addEventListener("progress", function(evt){
                if (evt.lengthComputable) {
                    var percentComplete = Math.floor((evt.loaded / evt.total)*100);
                    options.progress(percentComplete)
                }
            }, false);
            return xhr;
        },
        type: options.typeSend,
        url: options.file
    });
}

To use the function just insert so:

$("#btDownload").bind("click tap press",function(e){
   downloadFile({
        typeSend:"GET",
        file:"/path/path/file.mov",
        newfile:"nome-do-novo-arquivo.mov",
        abort:function(e){console.error("Abort:"+e)},
        error:function(e){console.error("Erro:"+e)},
        load:function(e){console.log("Load:"+e)},
        finish:function(e){console.log("Finish:"+e)},
        progress:function(e){
              $("#progressBar").css({width:e+'%'})
        }
    });
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.