Django用AJAX下载Excel文件

2024-06-23 02:27:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题,我找不到一个符合我需要的解决办法。在

当我点击一个按钮时,我有一个AJAX调用:

$.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));
                    }
                });

在视图.py公司名称:

^{pr2}$

如果我不使用AJAX(因为不使用AJAX时还有另一种情况),并且文件是在浏览器中下载的,但在这种情况下,我无法下载文件,它不会给出任何错误,但不会下载文件。在

如何强制下载文件?在


Tags: 文件urldatastringtype情况ajaxfunction
1条回答
网友
1楼 · 发布于 2024-06-23 02:27:52

我也有同样的问题。多亏了这个答案https://stackoverflow.com/a/47197970/9446730再加上一点点谷歌搜索,我就这样解决了:

    $('#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);
});

我们不能使用jqueryajax来下载这个blogpost中提到的文件。在

相关问题 更多 >