我正在用Django编写一个图像库,我想添加一个按钮来获得图像的高分辨率版本(低分辨率显示在详细信息页面中).如果我只放一个<a>链接,浏览器将打开图像而不是下载它.添加HTTP标头,如:
Content-Disposition: attachment; filename="beach008.jpg"
Run Code Online (Sandbox Code Playgroud)
工作,但因为它是一个静态文件,我不想用Django处理请求.目前,我正在使用NGINX来提供静态文件,动态页面通过FastCGI重定向到Django进程.我正在考虑使用NGINX add-header命令,但它可以设置该filename="xx"部分吗?或者也许有一些方法来处理Django中的请求,但是让NGINX服务内容?
Vas*_*sil 10
如果您的django应用程序由nginx代理,您可以使用x-accell-redirect.你需要在你的响应中传递一个特殊的标题,nginx会对此进行插入并开始提供文件,你也可以在同一个响应中传递Content-Disposition以强制下载.
如果您想控制哪些用户访问这些文件,那么该解决方案很好.
您还可以使用以下配置:
#files which need to be forced downloads
location /static/high_res/ {
root /project_root;
#don't ever send $request_filename in your response, it will expose your dir struct, use a quick regex hack to find just the filename
if ($request_filename ~* ^.*?/([^/]*?)$) {
set $filename $1;
}
#match images
if ($filename ~* ^.*?\.((jpg)|(png)|(gif))$) {
add_header Content-Disposition "attachment; filename=$filename";
}
}
location /static {
root /project_root;
}
Run Code Online (Sandbox Code Playgroud)
这将强制下载某些high_res文件夹(MEDIAROOT/high_rest)中的所有图像.而对于其他静态文件,它将表现得像平常一样.请注意,这是一个修改后的快速黑客,对我有用.它可能具有安全隐患,因此请谨慎使用.