使用StringIO,Django,Python使用HttpResponse返回Zip文件

时间:2018-08-14 15:51:15

标签: django python-2.7 zip httpresponse stringio

我试图使用StringIO()返回带有HttpResponse的zip文件,因为我没有存储在数据库或硬盘中。 我的问题是,当我请求文件时,响应返回200,但是OS从未询问我是否要保存文件,或者文件从未保存。我认为浏览器正在接收文件,因为我在网络活动(检查面板)上看到过,并且说返回的是6.4 MB的文件类型zip。 我正在从数据库的URL中获取一个.step文件(文本文件),提取内容,压缩并返回,仅此而已。

这是我的代码:

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

0 个答案:

没有答案