使用 Django 发送文件时出错 - 文件结果为空
Error sending a file using Django - file turns out empty
这是我的 views.py
个文件:
from django.http import HttpResponse
def render(request):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
response['X-Sendfile'] = '/files/filename.pdf'
# path relative to views.py
return response
当我运行服务器并请求
http://localhost:8080/somestring
我得到一个名为 somefilename.pdf
的空文件。我怀疑 render
.
中缺少一些关键部分
根据我的理解,此应用程序 views.py
之外的其他部分是正确的。
manage.py runserver
开发服务器不支持 X-Sendfile。在生产中,您需要为您的服务器(例如 Apache)启用 X-Sendfile。
您可能会找到 django-sendfile
package useful. It has a backend that you can use in development. However, it hasn't had a release in some time, and I found that I had to apply pull request 62 以获得 Python 3 支持。
这是解决我问题的代码:
from django.http import HttpResponse
from wsgiref.util import FileWrapper
def render(request):
response = HttpResponse(FileWrapper(open('file.pdf', 'rb')), content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
return response
这是我的 views.py
个文件:
from django.http import HttpResponse
def render(request):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
response['X-Sendfile'] = '/files/filename.pdf'
# path relative to views.py
return response
当我运行服务器并请求
http://localhost:8080/somestring
我得到一个名为 somefilename.pdf
的空文件。我怀疑 render
.
根据我的理解,此应用程序 views.py
之外的其他部分是正确的。
manage.py runserver
开发服务器不支持 X-Sendfile。在生产中,您需要为您的服务器(例如 Apache)启用 X-Sendfile。
您可能会找到 django-sendfile
package useful. It has a backend that you can use in development. However, it hasn't had a release in some time, and I found that I had to apply pull request 62 以获得 Python 3 支持。
这是解决我问题的代码:
from django.http import HttpResponse
from wsgiref.util import FileWrapper
def render(request):
response = HttpResponse(FileWrapper(open('file.pdf', 'rb')), content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
return response