This article mainly introduces the three ways to download files in Django. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.
1. Overview
In actual projects, the download function is often needed. , such as importing excel, pdf or file downloads. Of course, you can use web services to build your own resource servers that can be used for downloading, such as nginx. Here we mainly introduce file downloads in Django.
Implementation method: a tag + response header information (of course you can choose form implementation)
<p class="col-md-4"><a href="{% url 'download' %}" rel="external nofollow" >点我下载</a></p>
Method 1: Use HttpResponse
Routing url:
url(r'^download/',views.download,name="download"),
views.py code
from django.shortcuts import HttpResponse def download(request): file = open('crm/models.py', 'rb') response = HttpResponse(file) response['Content-Type'] = 'application/octet-stream' #设置头信息,告诉浏览器这是个文件 response['Content-Disposition'] = 'attachment;filename="models.py"' return response
Method 2: Use StreamingHttpResponse
Other logic remains unchanged, the main changes are in the back-end processing
from django.http import StreamingHttpResponse def download(request): file=open('crm/models.py','rb') response =StreamingHttpResponse(file) response['Content-Type']='application/octet-stream' response['Content-Disposition']='attachment;filename="models.py"' return response
Method Three: Using FileResponse
from django.http import FileResponse def download(request): file=open('crm/models.py','rb') response =FileResponse(file) response['Content-Type']='application/octet-stream' response['Content-Disposition']='attachment;filename="models.py"' return response
##Usage Summary
It is recommended to use FileResponse. It can be seen from the source code that FileResponse is a subclass of StreamingHttpResponse and uses iterators internally for data streaming.
The above is the detailed content of Detailed explanation of three ways to download files in Django_python. For more information, please follow other related articles on the PHP Chinese website!