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