Django提供下载文件

时间:2013-04-03 14:27:26

标签: python django file download

我正在尝试提供使用某些内容生成的txt文件,但我遇到了一些问题。我使用NamedTemporaryFile创建了临时文件并编写了内容,只需将delete设置为false即可调试,但下载的文件不包含任何内容。

我的猜测是响应值没有指向正确的文件,hense没有被下载,继承我的代码:

    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

4 个答案:

答案 0 :(得分:20)

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

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

答案 1 :(得分:3)

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

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

这里,path_to_file是文件的完整路径(不仅仅是文件的名称) 结帐django-snippet

答案 2 :(得分:1)

您的方法可能存在一些问题:

  • 不必刷新文件内容,如上面评论中所述添加f.flush()
  • NamedTemporaryFile在结束时被删除,当你退出你的功能时会发生什么,所以网络服务器没有机会拿起它
  • 临时文件名可能超出了Web服务器配置为使用X-Sendfile
  • 发送的路径

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

答案 3 :(得分:1)

import urllib2;   
url ="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chl=s&chld=H|0"; 
opener = urllib2.urlopen(url);  
mimetype = "application/octet-stream"
response = HttpResponse(opener.read(), mimetype=mimetype)
response["Content-Disposition"]= "attachment; filename=aktel.png"
return response 
相关问题