【发布时间】:2016-07-25 12:52:43
【问题描述】:
我尝试提供一个 (6KB) 生成的文件。我可以在开发中做到这一点,但不能在生产中做到:
我的看法是这样的:
def download_export_view(request, ref):
selection = models.Selection.objects.get(id=ref, user=request.user)
filename = ref + '.csv'
filepath = os.path.join(EXPORTS_DIR, filename)
wrapper = FileWrapper(open(filepath))
response = StreamingHttpResponse(FileWrapper(open(filepath), 8192),
content_type=mimetypes.guess_type(filepath)[0])
response['Content-Disposition'] = 'attachment; filename="%s"' % (filename,)
response['Content-Length'] = os.path.getsize(filepath)
return response
我确定文件路径是正确的,因为我得到 200 状态并且没有异常(如 FileNotFoundError),但我的浏览器没有获取该文件。
【问题讨论】:
-
我已经用 Chrome 进行了测试,它没有失败!但是开始下载需要很长时间。
-
最好的方法似乎是让 nginx 来完成这项工作。为此,我使用了 X-Accel-Redirect。就像stackoverflow.com/questions/28704712/… 我觉得这更合乎逻辑。
标签: django