Python-让Django提供可下载文件

发布于 2021-02-02 23:19:22

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

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

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

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

关注者
0
被浏览
116
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    你可以将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标头。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看