我希望网站上的用户能够下载路径模糊的文件,这样就无法直接下载.
例如,我希望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并查看以显示它?
为了"两全其美",您可以将S.Lott的解决方案与xsendfile module结合使用:Django生成文件(或文件本身)的路径,但实际的文件服务是由Apache/lighttpd处理的.设置mod_xsendfile后,与视图集成需要几行代码:
from django.utils.encoding import smart_str
response = HttpResponse(mimetype='application/force-download') # django 1.7的mimetype被content_类型取代
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
当然,这只有在你控制了你的服务器,或者你的托管公司已经设置了modxsendfile的情况下才有效.
EDIT:
django 1.7的mimetype被content_类型取代
response = HttpResponse(content_type='application/force-download')
EDIT:
对于nginx
判断this,它使用X-Accel-Redirect
而不是apache
X-Sendfile头.