代码之家  ›  专栏  ›  技术社区  ›  Ossama

Zip和服务器内存中的多个文件

  •  2
  • Ossama  · 技术社区  · 7 年前

    我目前正在使用下面的代码生成word文档,然后使用cherrypy在web上提供此文档。

    tpl.get_docx().save(iostream)
    cherrypy.response.headers['Content-Type'] = (
                'application/vnd.openxmlformats-officedocument'
                '.wordprocessingml.document'
                )
    cherrypy.response.headers['Content-Disposition'] = (
                'attachment; filename={fname}.docx'.format(
                    fname='SP' + kwargs['sp'] + '-'+ kwargs['WO'] + ' ' + kwargs['site'] + ' - ' + 'RPC Report'  +'.docx'
                )
                )
    iostream.seek(0)
    return file_generator(iostream)
    

    import zipfile
    import StringIO
    
    zipped_file = StringIO.StringIO()
    with zipfile.ZipFile(zipped_file, 'w') as zip:
        for i, file in enumerate(files):
            file.seek(0)
            zip.writestr("{}.csv".format(i), file.read())
    
    zipped_file.seek(0)
    
    1 回复  |  直到 7 年前
        1
  •  5
  •   Ossama    7 年前

    经过几个小时的坚持,我终于成功了

    iostream = BytesIO()
    tpl.get_docx().save(iostream)
    
    iostream1 = BytesIO()
    tpl1.get_docx().save(iostream1)
    
    zip_output = StringIO.StringIO()
    file = zipfile.ZipFile(zip_output, "w")
    file.writestr("test.docx", iostream.getvalue())
    file.writestr("test1.docx", iostream1.getvalue())
    file.close()
    
    cherrypy.response.headers['Content-Type'] = 'application/zip'
    cherrypy.response.headers['Content-Disposition'] = 'attachment; filename="test.zip"'
    
    return zip_output.getvalue()