How to send zip files in the python Flask framework?

后端 未结 1 1059
梦毁少年i
梦毁少年i 2020-11-28 10:30

I have a flask server that grabs binary data for several different files from a database and puts them into a python \'zipfile\' object. I want to send the generated zip fi

相关标签:
1条回答
  • 2020-11-28 11:03

    BytesIO() needs to be passed bytes data, but a ZipFile() object is not bytes-data; you actually created a file on your harddisk.

    You can create a ZipFile() in memory by using BytesIO() as the base:

    memory_file = BytesIO()
    with zipfile.ZipFile(memory_file, 'w') as zf:
        files = result['files']
        for individualFile in files:
            data = zipfile.ZipInfo(individualFile['fileName'])
            data.date_time = time.localtime(time.time())[:6]
            data.compress_type = zipfile.ZIP_DEFLATED
            zf.writestr(data, individualFile['fileData'])
    memory_file.seek(0)
    return send_file(memory_file, attachment_filename='capsule.zip', as_attachment=True)
    

    The with statement ensures that the ZipFile() object is properly closed when you are done adding entries, causing it to write the required trailer to the in-memory file object. The memory_file.seek(0) call is needed to 'rewind' the read-write position of the file object back to the start.

    0 讨论(0)
提交回复
热议问题