2010-02-05 47 views
3

我正嘗試創建一個使用Django提供可下載內容的簡單方法。這個想法是,登錄的用戶應該能夠通過lighttpd下載(相當大的)文件。用Django和lighttpd提供服務文件

在這裏有幾個關於這方面的文章,我也通過一個簡單的解決方案穿越blog post

我在上面提到的鏈接中創建了一個視圖(並且在lighttpd配置文件中添加了「allow-x-send-file」=>「enable」),它「起作用」。當我用Firebug檢查標題時,我得到正確的內容類型,文件長度和200 OK,但沒有下載文件。

然後我找到了解決方案here on SO, where additional headers are sent。現在提供了一個文件,但下載的文件是空的。標題仍然正確。

這裏是我的源(除去auth_decorators並沒有處理不存在的文件):

import os 
import mimetypes 
import django.http 

from django.conf import settings 

def get_absolute_filename(filename='', safe=True): 
    if not filename: 
     return os.path.join(settings.FILE_DOWNLOAD_PATH, 'index') 
    if safe and '..' in filename.split(os.path.sep): 
     return get_absolute_filename(filename='') 
    return os.path.join(settings.FILE_DOWNLOAD_PATH, filename) 

def retrieve_file(request, filename=''): 
    abs_filename = get_absolute_filename(filename) 
    response = django.http.HttpResponse(mimetype='application/force-download') 
    response['X-Sendfile'] = abs_filename 
    response['Content-Disposition'] = 'attachment; filename=%s' % abs_filename 
    response['Content-Type'] = mimetypes.guess_type(abs_filename) 
    response['Content-Length'] = os.path.getsize(abs_filename) 
    return response 
+1

另外,請使用'python-magic'而不是'mimetypes'。 – 2010-02-05 20:43:55

+1

是的,我喜歡。爲什麼? – vorpyg 2010-02-05 21:08:10

回答

1

看看你的來源 - 你發送任何文件,只有頭。

+0

我明白了!我想我應該將文件傳遞給HttpResponse對象。 Ref http://docs.djangoproject.com/zh/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment – vorpyg 2010-02-05 21:16:53

0

lighttpd的1.5版之前的版本使用X-LIGHTTPD-send-file頭。