Django download file empty

心不动则不痛 提交于 2019-12-12 10:06:28

问题


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 download 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!


回答1:


I answered this question here, hope it helps.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/3141682/django-download-file-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!