Download Excel or other binary file with loader or progress meter using JQuery without using Cookies

1.2k Views Asked by At

How do you show the user a "loading" widget or progress meter while downloading an Excel or other binary file using JQuery without using cookies?

1

There are 1 best solutions below

0
On BEST ANSWER
    $.ajax(url, {
        xhrFields: {
            responseType: 'arraybuffer'
        },
        success: function(data, textStatus, jqXHR) {
            var blob = new Blob([data], {type: jqXHR.getResponseHeader('content-type')});
            var fileName = jqXHR.getResponseHeader('content-disposition').split('filename=')[1].split(';')[0];
            saveAs(blob, fileName);
        },
        progress: function(e) {
            if (e.lengthComputable) {
                const completedPercentage = Math.round((e.loaded * 100) / e.total);
                if (completedPercentage >= 100) {
                    $("#loader").dialog("close");
                }
            }
            else {
                if (console) {
                    console.log('Content length not reported. Fix this server side.');    
                }
            }
        }
    });

The Fetch API seems to be a much better way to pull a binary file via ajax, but does not support IE which is a requirement for me. Here is the code I looked at in case it helps anyone. I didn't add the close "loader" logic, but I'm pretty sure you could do that right before or after saving the file.

    fetch(url, {
        responseType: 'blob'
    }).then(response => response.blob())
      .then(blob => saveAs(blob, 'test.xlsx'));

This answer was pieced together from the web and several SO posts. See below for relevant links: