how to stream file to client in django

前端 未结 2 1626
孤城傲影
孤城傲影 2021-01-07 02:13

I want to know how can I stream data to client using django.

The Goal

The user submits a form, the form data is passed to a web service whi

2条回答
  •  攒了一身酷
    2021-01-07 02:55

    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
    

提交回复
热议问题