[英]How do I download xlsx file with Django?
I tried to make a button for downloading a .xlsx
file using Django so I followed this tutorial: https://xlsxwriter.readthedocs.io/example_django_simple.html我试图制作一个使用 Django 下载
.xlsx
文件的按钮,所以我遵循了本教程: https : //xlsxwriter.readthedocs.io/example_django_simple.html
Now I have an HTTP response, but no download prompt is showing.现在我有一个 HTTP 响应,但没有显示下载提示。
Here are some parts of my code :这是我的代码的一些部分:
views.py:视图.py:
def xlsx(request):
if request.method == "POST":
output = io.BytesIO()
workbook = xlsxwriter.Workbook(output)
worksheet = workbook.add_worksheet("hello")
worksheet.write(0,0, 'Client')
workbook.close()
output.seek(0)
filename = 'EdedocBilling.xlsx'
response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
return response
index.html索引.html
<form>...</form>
<button type = "button" id = "saveID"
onclick = "$.ajax({
type: 'POST',
url: 'xlsx',
async: false,
data: $('form').serialize(),
success : console.log(' Success')
})">
Generate
</button>
I removed the code where I process the data because the generated .xlsx
works fine.我删除了处理数据的代码,因为生成的
.xlsx
工作正常。 (I tested creating the file on the server and it worked.) (我测试了在服务器上创建文件并成功。)
Here are the HTTP response headers:以下是 HTTP 响应标头:
HTTP/1.1 200 OK
Date: Thu, 08 Jul 2021 14:47:37 GMT
Server: WSGIServer/0.2 CPython/3.8.8
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Content-Disposition: attachment; filename="EdedocBilling.xlsx"
X-Frame-Options: DENY
Content-Length: 5252
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Does somebody have a solution?有人有解决方案吗? Thanks!
谢谢!
This is due to the nature of AJAX, and how browsers handle all of this.这是由于 AJAX 的性质以及浏览器如何处理所有这些。
Have a look at the different answers to question Is it possible to download a file with HTTP POST?查看问题的不同答案是否可以使用 HTTP POST 下载文件? .
.
Return a URL in the response of the POST request and implement a URL pattern that delivers the file content.在 POST 请求的响应中返回一个 URL,并实现一个传递文件内容的 URL 模式。
This is of course a bit more effort but it would be a good solution if you website has to scale.这当然需要更多的努力,但如果您的网站必须扩展,这将是一个很好的解决方案。
Steps:脚步:
get_absolute_url()
on your model returning this route.get_absolute_url()
。 In a production setup, you can also configure your Reverse Proxy (eg nginx) to deliver the files, and your Django view only sets a header (X-Accel-Redirect) that indicates to the proxy which file to deliver.在生产设置中,您还可以配置您的反向代理(例如 nginx)来交付文件,并且您的 Django 视图仅设置一个标头(X-Accel-Redirect),指示代理要交付哪个文件。 See https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/ for more on this.
有关更多信息,请参阅https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/ 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.