让 Django 提供可下载的文件 [英] Having Django serve downloadable files

查看:33
本文介绍了让 Django 提供可下载的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望网站上的用户能够下载路径被遮挡的文件,因此无法直接下载.

I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.

例如,我希望 URL 是这样的:http://example.com/download/?f=somefile.txt

For instance, I'd like the URL to be something like this: http://example.com/download/?f=somefile.txt

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

And on the server, I know that all downloadable files reside in the folder /home/user/files/.

有没有办法让 Django 提供该文件以供下载,而不是尝试查找 URL 并查看以显示它?

Is there a way to make Django serve that file for download as opposed to trying to find a URL and View to display it?

推荐答案

为了两全其美",您可以将 S.Lott 的解决方案与 xsendfile 模块:django 生成文件的路径(或文件本身),但实际的文件服务由 Apache/Lighttpd 处理.设置 mod_xsendfile 后,与您的视图集成需要几行代码:

For the "best of both worlds" you could combine S.Lott's solution with the xsendfile module: django generates the path to the file (or the file itself), but the actual file serving is handled by Apache/Lighttpd. Once you've set up mod_xsendfile, integrating with your view takes a few lines of code:

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 时才有效.

Of course, this will only work if you have control over your server, or your hosting company has mod_xsendfile already set up.

django 1.7 的 mimetype 被 content_type 替换

mimetype is replaced by content_type for django 1.7

response = HttpResponse(content_type='application/force-download')  

对于 nginx 检查 this,它使用 X-Accel-Redirect 而不是 apache X-Sendfile 标头.

For nginx check this, it uses X-Accel-Redirect instead of apache X-Sendfile header.

这篇关于让 Django 提供可下载的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆