我希望网站上的用户能够下载路径被遮蔽的文件,这样他们就不能直接下载。
例如,我希望URL是这样的:http://example.com/download/?f=somefile.txt
在服务器上,我知道所有可下载的文件都位于/home/user/files/文件夹中。
有没有一种方法可以让Django为下载提供这个文件,而不是试图找到一个URL和视图来显示它?
我希望网站上的用户能够下载路径被遮蔽的文件,这样他们就不能直接下载。
例如,我希望URL是这样的:http://example.com/download/?f=somefile.txt
在服务器上,我知道所有可下载的文件都位于/home/user/files/文件夹中。
有没有一种方法可以让Django为下载提供这个文件,而不是试图找到一个URL和视图来显示它?
当前回答
def qrcodesave(request):
import urllib2;
url ="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chl=s&chld=H|0";
opener = urllib2.urlopen(url);
content_type = "application/octet-stream"
response = HttpResponse(opener.read(), content_type=content_type)
response["Content-Disposition"]= "attachment; filename=aktel.png"
return response
其他回答
S.Lott有“好的”/简单的解决方案,elo80ka有“最好的”/高效的解决方案。这是一个“更好”/中间的解决方案-没有服务器设置,但更有效的大文件比天真的修复:
http://djangosnippets.org/snippets/365/
基本上,Django仍然处理文件的服务,但不会一次将整个文件加载到内存中。这允许您的服务器(缓慢地)在不增加内存使用的情况下提供大文件。
同样,S.Lott的X-SendFile对于较大的文件仍然更好。但如果你不能或不想为此费心,那么这个中间解决方案将为你带来更好的效率,而不会带来麻烦。
def qrcodesave(request):
import urllib2;
url ="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chl=s&chld=H|0";
opener = urllib2.urlopen(url);
content_type = "application/octet-stream"
response = HttpResponse(opener.read(), content_type=content_type)
response["Content-Disposition"]= "attachment; filename=aktel.png"
return response
对于一个非常简单但不是有效或可扩展的解决方案,你可以使用内置的django serve视图。这对于快速原型或一次性工作是非常好的,但正如在这个问题中所提到的,你应该在生产中使用apache或nginx之类的东西。
from django.views.static import serve
filepath = '/some/path/to/local/file.txt'
return serve(request, os.path.basename(filepath), os.path.dirname(filepath))
试一试:https://pypi.python.org/pypi/django-sendfile/
“一旦Django检查了权限,抽象的卸载文件上传到web服务器(例如Apache的mod_xsendfile)。”
为了“两全皆美”,你可以将s.l ot的解决方案与xsendfile模块结合起来:django生成文件的路径(或文件本身),但实际的文件服务由Apache/Lighttpd处理。一旦你设置了mod_xsendfile,集成你的视图需要几行代码:
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的情况下才会起作用。
编辑:
在django 1.7中,Mimetype被content_type取代
response = HttpResponse(content_type='application/force-download')
编辑: 对于nginx检查,它使用X-Accel-Redirect而不是apache的X-Sendfile头。