2008-11-04 119 views
9

我正在用Django編寫圖像庫,並且我想添加一個按鈕以獲取圖像的高分辨率版本(低分辨率顯示在詳細信息頁面中) 。如果我只放一個<a>鏈接,瀏覽器將打開圖像而不是下載它。添加一個HTTP頭如:與Django靜態文件的自定義HTTP標頭

Content-Disposition: attachment; filename="beach008.jpg" 

工作,但由於它是一個靜態文件,我不想用Django處理請求。目前,我使用NGINX來提供靜態文件,動態頁面通過FastCGI重定向到Django進程。我正在考慮使用NGINX add-header命令,但它可以設置filename="xx"部分?或者也許有辦法在Django中處理請求,但是讓NGINX提供內容?

回答

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; 
     } 

     if ($filename ~* ^.*?\.(jpg)|(png)|(gif)$){ 
         add_header Content-Disposition "attachment; filename=$filename"; 
        } 
     } 

    location /static { 
     root /project_root; 
    } 

這將迫使一些high_res文件夾(介質根/ high_rest)所有圖像下載。而對於其他靜態文件,它將表現得像正常一樣。請注意,這是一個修改後的快速入侵,適合我。它可能有安全隱患,所以謹慎使用它。

+0

太棒了!正是我所期待的。 – Javier 2008-12-22 17:48:07

4

我寫了一個簡單的裝飾,爲django.views.static.serve視圖

這對我來說完美的作品。

def serve_download(view_func): 
    def _wrapped_view_func(request, *args, **kwargs): 
     response = view_func(request, *args, **kwargs) 
     response['Content-Type'] = 'application/octet-stream'; 
     import os.path 
     response['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(kwargs['path']) 
     return response 
    return _wrapped_view_func 

您也可以使用nginx的MIME類型

​​

該解決方案並沒有爲我工作玩,因爲我想有直接聯繫的文件(這樣用戶可以查看圖像,例如)和下載鏈接。

0

我現在正在做的是使用不同的URL下載比「意見」,並添加文件名作爲URL ARG:

通常媒體鏈接:http://xx.com/media/images/lores/f_123123.jpg 下載鏈接:http://xx.com/downs/hires/f_12323?beach008.jpg

和nginx的具有這樣的配置:

location /downs/ { 
     root /var/www/nginx-attachment; 
     add_header Content-Disposition 'attachment; filename="$args"'; 
    } 

,但我真的不喜歡它的味道。