我希望网站上的用户能够下载路径被遮挡的文件,因此无法直接下载它们。
例如,我希望 URL 是这样的:http://example.com/download/?f=somefile.txt
在服务器上,我知道所有可下载的文件都位于该文件夹中/home/user/files/
.
有没有办法让 Django 提供该文件以供下载,而不是尝试查找 URL 和视图来显示它?
为了实现“两全其美”,您可以将 S.Lott 的解决方案与: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 时,这才有效。
EDIT:
django 1.7 中 mimetype 被 content_type 取代
response = HttpResponse(content_type='application/force-download')
EDIT:
For nginx
check this https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/, 它用X-Accel-Redirect
代替apache
X-Sendfile 标头。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)