简体   繁体   中英

Django download Excel File with AJAX

I have a problem that I can't find nowhere a solution that match what I need.

I have this AJAX call when I click on a button:

$.ajax({
                    type: 'POST',
                    url: '{% url "tests" %}',
                    traditional: true,
                    data : {'mydata': list,"excel": "" },
                    success: function (data, textStatus) {
                        //Test
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert("some error " + String(errorThrown) + String(textStatus) + String(XMLHttpRequest.responseText));
                    }
                });

And in the views.py:

if request.method == "POST" and request.is_ajax():
        if 'excel' in request.POST:
            data = request.POST.getlist('mydata')
            if data:
                tests = Test.objects.filter(pk__in=data)
                response = HttpResponse(content_type='application/vnd.ms-excel')
                response['Content-Disposition'] = 'attachment; filename=Test.xlsx'
                xlsx_data = WriteToExcelTests(tests)
                response.write(xlsx_data)
                return response

This works fine if I do not use AJAX (because I have another case when I don't use AJAX) and the file is downloaded in the browser but in this case I can't download the file, it does not give any error but it does not download the file.

How can I force this to download the file?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM