开发者

Django download file empty

I am writing a simple function for downloading a certain file, from the server, to my machine. The file is unique represented by its id. The file is locatd corectly, and the do开发者_开发知识库wnload is done, but the downloaded file (though named as the one on the server) is empty. my download function looks like this:

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

where can i be wrong? thanks!


I answered this question here, hope it helps.


Looks like you're not sending any data (you don't even open the file).

Django has a nice wrapper for sending files (code taken from 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

so you could use something like response = HttpResponse(FileWrapper(file(path_to_file)), mimetype='application/force-download').

If you are really using lighttpd (because of the "X-Sendfile" header), you should check the server and FastCGI configuration, I guess.


Try one of these approaches:

1) Disable GZipMiddleware if you are using it;

2) Apply a patch to django/core/servers/basehttp.py described in https://code.djangoproject.com/ticket/6027

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜