这是我的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
之外的其他部分是正确的。
最佳答案
这是解决我问题的代码:
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
关于django - 使用 Django 发送文件时出错 - 文件结果为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46106006/