小编典典

让Django提供可下载文件

django

我希望站点上的用户能够下载路径被遮盖的文件,以便不能直接下载它们。

例如,我希望URL如下所示: http://example.com/download/?f=somefile.txt

在服务器上,我知道所有可下载文件都位于文件夹中/home/user/files/

有没有一种方法可以使Django提供该文件供下载,而不是尝试查找URL和查看以显示它?


阅读 906

收藏
2020-03-25

共1个答案

小编典典

对于“两全其美”,你可以将S.Lott的解决方案与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而不是apacheX-Sendfile标头。

2020-03-25