我正在编写一个简单的函数,用于从服务器下载某个文件到我的机器。 该文件唯一由其ID表示。该文件是coreatly locatd,下载完成,但下载的文件(虽然命名为服务器上的文件)是空的。 我的下载功能如下:
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
哪里可以错?谢谢!
答案 0 :(得分:2)
看起来你没有发送任何数据(你甚至没有打开文件)。
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 :(得分:2)
我回答了这个问题here,希望有所帮助。
答案 2 :(得分:1)
尝试以下方法之一:
1)如果您正在使用它,请禁用GZipMiddleware;
2)将补丁应用于中所述的django / core / servers / basehttp.py https://code.djangoproject.com/ticket/6027