[Django]-Django download Excel File with AJAX

8๐Ÿ‘

โœ…

I had the same Problem. Thanks to this answer https://stackoverflow.com/a/47197970/9446730 and little bit of googling I solved it like this:

    $('#download_btn').on('click', e => {
    // random data
    let data = 'mydata=foo&excel=bar';
    let request = new XMLHttpRequest();
    request.open('POST', '{% url "tests" %}', true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    request.responseType = 'blob';

    request.onload = function (e) {
        if (this.status === 200) {
            let filename = "";
            let disposition = request.getResponseHeader('Content-Disposition');
            // check if filename is given
            if (disposition && disposition.indexOf('attachment') !== -1) {
                let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                let matches = filenameRegex.exec(disposition);
                if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
            }
            let blob = this.response;
            if (window.navigator.msSaveOrOpenBlob) {
                window.navigator.msSaveBlob(blob, filename);
            }
            else {
                let downloadLink = window.document.createElement('a');
                let contentTypeHeader = request.getResponseHeader("Content-Type");
                downloadLink.href = window.URL.createObjectURL(new Blob([blob], {type: contentTypeHeader}));
                downloadLink.download = filename;
                document.body.appendChild(downloadLink);
                downloadLink.click();
                document.body.removeChild(downloadLink);
            }
        } else {
            alert('Download failed.')
        }
    };
    request.send(data);
});

We cannot use Jquery Ajax to download file as mentioned in this blogpost.

๐Ÿ‘คbinaryEcon

Leave a comment