我正在尝试使用Django创建一种简单的方式来提供可下载内容。这个想法是已登录用户可以通过lighttpd下载(相当大的)文件。
在SO上有几篇关于此问题的帖子,我还看到了一个博客文章提供了一个简单的解决方案。
我按照上述链接中的视图创建了一个视图(并将“allow-x-send-file”=>“enable”添加到lighttpd配置中),它“工作”,但是存在问题。当我使用Firebug检查标头时,我得到了正确的内容类型、文件长度和200 OK,但没有文件被下载。
然后我在SO上找到了一个解决方案,其中发送了额外的标头。现在文件已经被提供,但下载的文件为空。标头仍然是正确的。
以下是我的源代码(去除了auth_decorators并且没有处理不存在的文件):
在SO上有几篇关于此问题的帖子,我还看到了一个博客文章提供了一个简单的解决方案。
我按照上述链接中的视图创建了一个视图(并将“allow-x-send-file”=>“enable”添加到lighttpd配置中),它“工作”,但是存在问题。当我使用Firebug检查标头时,我得到了正确的内容类型、文件长度和200 OK,但没有文件被下载。
然后我在SO上找到了一个解决方案,其中发送了额外的标头。现在文件已经被提供,但下载的文件为空。标头仍然是正确的。
以下是我的源代码(去除了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
python-magic
代替mimetypes
。 - Ignacio Vazquez-Abrams