您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python-让Django提供可下载文件

Python-让Django提供可下载文件

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

python 2022/1/1 18:20:03 有585人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶