Python Django使用AJAX下载Excel文件
我有一个问题,我找不到任何符合我需要的解决方案 当我点击一个按钮时,我有一个AJAX调用:Python Django使用AJAX下载Excel文件,python,ajax,django,Python,Ajax,Django,我有一个问题,我找不到任何符合我需要的解决方案 当我点击一个按钮时,我有一个AJAX调用: $.ajax({ type: 'POST', url: '{% url "tests" %}', traditional: true, data : {'mydata': list,"excel": "" },
$.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));
}
});
在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
如果我不使用AJAX(因为我不使用AJAX时还有另一种情况),并且文件是在浏览器中下载的,但在这种情况下我无法下载文件,它不会给出任何错误,但不会下载文件
如何强制下载该文件?我也有同样的问题。多亏了这个答案和一点谷歌搜索,我就这样解决了这个问题:
$('#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);
});
我们无法使用Jquery Ajax下载本文中提到的文件。我怀疑您的if块没有运行。通过添加
print('Entered if block')
,您可以非常快速地测试这一点。如果是这样的话,那么解决方案就是If request.is_ajax():request.POST=json.loads(request.body.decode('utf-8'))data=request.POST.getlist('mydata')
我已经调试并确保它工作正常,但它只是响应,什么也不做……我尝试了在互联网上找到的一切。但只是你的代码起作用了。非常感谢你。我尝试的其他方法使我的.xlsx变得腐败。