how to stream file to client in django

会有一股神秘感。 提交于 2019-12-02 02:50:10

You can create a django file instance of ContentFile using a string content instead of actual file and then send it as a response.

Sample code:

from django.core.files.base import ContentFile
def your_view(request):
    #your view code
    string_to_return = get_the_string() # get the string you want to return.
    file_to_send = ContentFile(string_to_return)
    response     = HttpResponse(file_to_send,'application/x-gzip')
    response['Content-Length']      = file_to_send.size    
    response['Content-Disposition'] = 'attachment; filename="somefile.tar.gz"'
    return response   

You can modify send_zipfile from the snippet to suit your needs. Just use StringIO to turn your string into a file-like object which can be passed to FileWrapper.

import StringIO, tempfile, zipfile
...
# get your string from the webservice
string = webservice.get_response() 
...
temp = tempfile.TemporaryFile()

# this creates a zip, not a tarball
archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)

# this converts your string into a filelike object
fstring = StringIO.StringIO(string)   

# writes the "file" to the zip archive
archive.write(fstring)
archive.close()

wrapper = FileWrapper(temp)
response = HttpResponse(wrapper, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=test.zip'
response['Content-Length'] = temp.tell()
temp.seek(0)
return response
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!