我正在编写一个简单的功能,用于下载从服务器到我的计算机的某个文件。该文件以其ID表示唯一。该文件是corectly的,并且下载完成,但是下载的文件(尽管在服务器上被称为该文件)是空的。我的下载功能看起来像这样:

def download_course(request, id):
    course = Courses.objects.get(pk = id).course
    path_to_file = 'root/cFolder'
    filename = __file__ # Select your file here.                                
    wrapper = FileWrapper(file(filename))
    content_type = mimetypes.guess_type(filename)[0]
    response = HttpResponse(wrapper, content_type = content_type)
    response['Content-Length'] = os.path.getsize(filename)
    response['Content-Disposition'] = 'attachment; filename=%s/' % smart_str(course)

    return response

我在哪里可以错?谢谢!

有帮助吗?

解决方案

我回答了这个问题 这里, , 希望能帮助到你。

其他提示

看来您没有发送任何数据(您甚至没有打开文件)。

Django有一个不错的包装器,用于发送文件(从中获取代码 djangosnippets.org):

def send_file(request):
    """                                                                         
    Send a file through Django without loading the whole file into              
    memory at once. The FileWrapper will turn the file object into an           
    iterator for chunks of 8KB.                                                 
    """
    filename = __file__ # Select your file here.                                
    wrapper = FileWrapper(file(filename))
    response = HttpResponse(wrapper, content_type='text/plain')
    response['Content-Length'] = os.path.getsize(filename)
    return response

所以你可以使用类似的东西 response = HttpResponse(FileWrapper(file(path_to_file)), mimetype='application/force-download').

如果您真的在使用LightTPD(因为 “ X-Sendfile” 标题),我想您应该检查服务器和FastCGI配置。

尝试以下方法之一:

1)禁用GZIPMIDDLEWARE(如果使用);

2)在Django/core/servers/basehttp.py上应用一个补丁https://code.djangoproject.com/ticket/6027

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top