Python Django 提供下载文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15790136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django Serving a Download File
提问by Callum
I'm trying to serve a txt file generated with some content and i am having some issues. I'vecreated the temp files and written the content using NamedTemporaryFile and just set delete to false to debug however the downloaded file does not contain anything.
我正在尝试提供一个由一些内容生成的 txt 文件,但我遇到了一些问题。我已经创建了临时文件并使用 NamedTemporaryFile 编写了内容,然后将 delete 设置为 false 进行调试,但下载的文件不包含任何内容。
My guess is the response values are not pointed to the correct file, hense nothing is being downloaded, heres my code:
我的猜测是响应值没有指向正确的文件,因此没有下载任何内容,这是我的代码:
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
采纳答案by Ric
Have you considered just sending p.bodythrough the responselike this:
你有没有考虑p.body过response像这样发送:
response = HttpResponse(mimetype='text/plain')
response['Content-Disposition'] = 'attachment; filename="%s.txt"' % p.uuid
response.write(p.body)
回答by karthikr
XSend requires the path to the file in
response['X-Sendfile']So, you can do
XSend 需要文件的路径
response['X-Sendfile']所以,你可以这样做
response['X-Sendfile'] = smart_str(path_to_file)
Here, path_to_fileis the full path to the file (not just the name of the file)
Checkout this django-snippet
在这里,path_to_file是文件的完整路径(不仅仅是文件名)签出这个django-snippet
回答by Michal ?iha?
There can be several problems with your approach:
您的方法可能存在几个问题:
- file content does not have to be flushed, add
f.flush()as mentioned in comment above NamedTemporaryFileis deleted on closing, what might happen just as you exit your function, so the webserver has no chance to pick it up- temporary file name might be out of paths which web server is configured to send using
X-Sendfile
- 文件内容不必刷新,
f.flush()如上面评论中所述添加 NamedTemporaryFile在关闭时被删除,当您退出函数时可能会发生什么,因此网络服务器没有机会拿起它- 临时文件名可能不在 Web 服务器配置为使用的路径之外
X-Sendfile
Maybe it would be better to use StreamingHttpResponseinstead of creating temporary files and X-Sendfile...
也许使用StreamingHttpResponse而不是创建临时文件会更好X-Sendfile......
回答by Saurabh Chandra Patel
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

