Download zip file with HttpResponse Django StringIO ()

0

I am trying to return a zip file with HttpResponse , using StringIO because I am not storing it in the database or on the hard drive. My problem is that my answer is 200 when I request the file, but the browser never asks me if I want to save the file, or the file is never saved. I think the browser is receiving the file because I have seen it in the Network Activity (inspect panel) and it says that a zip file of 6.4 MB is returned. I'm taking a .step file (text file) from the URL of a DB, extracting the content, compressing and coming back, that's all.

this is my code:

def function(request, url_file = None):

    #retrieving info
    name_file = url_file.split('/')[-1]
    file_content = urllib2.urlopen(url_file).read()
    stream_content = StringIO(file_content)
    upload_name = name_file.split('.')[0]

    # Create a new stream and write to it

    write_stream = StringIO()
    zip_file = ZipFile(write_stream, "w")
    try:
        zip_file.writestr(name_file, stream_content.getvalue().encode('utf-8'))
    except:
        zip_file.writestr(name_file, stream_content.getvalue().encode('utf-8', 'ignore'))

    zip_file.close()

    response = HttpResponse(write_stream.getvalue(), mimetype="application/x-zip-compressed")
    response['Content-Disposition'] = 'attachment; filename=%s.zip' % upload_name
    response['Content-Language'] = 'en'
    response['Content-Length'] = write_stream.tell()

    return response
    
asked by juan jose Palacio 15.08.2018 в 16:56
source

0 answers