繁体   English   中英

Django提供下载文件

[英]Django Serving a Download File

我正在尝试提供一些内容生成的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

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

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

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

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

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

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

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

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

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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM