[Django]-File downloaded always blank in Python, Django

8👍

✅

You have to move the pointer to the beginning of the buffer with seek and use flush just in case the writing hasn’t performed.

from django.core.servers.basehttp import FileWrapper
import StringIO

def aux_pizarra(request):

    myfile = StringIO.StringIO()
    myfile.write("hello")       
    myfile.flush()
    myfile.seek(0) # move the pointer to the beginning of the buffer
    response = HttpResponse(FileWrapper(myfile), content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename=prueba.txt'
    return response

This is what happens when you do it in a console:

>>> import StringIO
>>> s = StringIO.StringIO()
>>> s.write('hello')
>>> s.readlines()
[]
>>> s.seek(0)
>>> s.readlines()
['hello']

There you can see how seek is necessary to bring the buffer pointer to the beginning for reading purposes.

Hope this helps!

Leave a comment