Django提供下载文件

2024-03-28 18:12:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图提供一个txt文件生成的一些内容,我有一些问题。我创建了临时文件并使用NamedTemporaryFile编写了内容,只是将delete设置为false进行调试,但是下载的文件不包含任何内容。

我的猜测是响应值没有指向正确的文件,因此没有下载任何内容,下面是我的代码:

    f = NamedTemporaryFile()
    f.write(p.body)

    response = HttpResponse(FileWrapper(f), mimetype='application/force-download')
    response['Content-Disposition'] = 'attachment; filename=test-%s.txt' % p.uuid
    response['X-Sendfile'] = f.name

Tags: 文件代码txtfalse内容responsebodydelete
3条回答

你是否考虑过像这样通过response发送p.body

response = HttpResponse(mimetype='text/plain')
response['Content-Disposition'] = 'attachment; filename="%s.txt"' % p.uuid
response.write(p.body)

你的方法可能有几个问题:

  • 不必刷新文件内容,添加上面注释中提到的f.flush()
  • NamedTemporaryFile在关闭时被删除,当您退出函数时可能会发生什么,因此web服务器没有机会获取它
  • 临时文件名可能超出了web服务器配置为使用X-Sendfile发送的路径

也许最好使用StreamingHttpResponse而不是创建临时文件和X-Sendfile。。。

XSend需要中文件的路径 response['X-Sendfile'] 所以,你可以

response['X-Sendfile'] = smart_str(path_to_file)

这里,path_to_file是文件的完整路径(不仅仅是文件名) 签出这个django-snippet

相关问题 更多 >