让Django提供可下载的文件 [英] Having Django serve downloadable files

查看:128
本文介绍了让Django提供可下载的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望网站上的用户能够下载其路径被遮掩的文件,因此无法直接下载。

I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.

例如,我想要的URL要这样做, http://example.com/download/?f=somefile。 txt

For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt

在服务器上,我知道所有可下载的文件都位于一个文件夹/ home / user / files /\".

And on the server, I know that all downloadable files reside in a folder "/home/user/files/".

有没有办法使Django提供该文件下载,而不是试图找到一个URL和View来显示?

Is there a way to make Django serve that file for download as opposed to trying to find a URL and View to display it?

推荐答案

对于最好的两个世界,您可以将S.Lott的解决方案与 xsendfile模块:django生成文件(或文件本身)的路径,但实际的文件服务由Apache / Lighttp处理d。一旦您设置了mod_xsendfile,与您的视图集成就需要几行代码:

For the "best of both worlds" you could combine S.Lott's solution with the xsendfile module: django generates the path to the file (or the file itself), but the actual file serving is handled by Apache/Lighttpd. Once you've set up mod_xsendfile, integrating with your view takes a few lines of code:

from django.utils.encoding import smart_str

response = HttpResponse(mimetype='application/force-download') # mimetype is replaced by content_type for django 1.7
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
response['X-Sendfile'] = smart_str(path_to_file)
# It's usually a good idea to set the 'Content-Length' header too.
# You can also set any other required headers: Cache-Control, etc.
return response

当然,这只有在您可以控制您的服务器,或您的托管公司已经设置了mod_xsendfile的情况下才有效。

Of course, this will only work if you have control over your server, or your hosting company has mod_xsendfile already set up.

编辑:


mimetype被django 1.7的内容替换为

mimetype is replaced by content_type for django 1.7



response = HttpResponse(content_type='application/force-download'

这篇关于让Django提供可下载的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆