如何使用Flask send\u fi下载inmemoryZIPFILE对象

2024-04-25 04:33:50 发布

您现在位置:Python中文网/ 问答频道 /正文

Flask HTTP服务器正在运行server.py

import os, io, zipfile, time

from flask import Flask, request, send_file

app = Flask(__name__)

FILEPATH = '/change/it/to/any_file.path'

@app.route('/download', methods=['GET','POST'])
def download():     
    fileobj = io.BytesIO()
    with zipfile.ZipFile(fileobj, 'w') as zip_file:
        zip_info = zipfile.ZipInfo(FILEPATH)
        zip_info.date_time = time.localtime(time.time())[:6]
        zip_info.compress_type = zipfile.ZIP_DEFLATED
        with open(FILEPATH, 'rb') as fd:
            zip_file.writestr(zip_info, fd.read())
    fileobj.seek(0)

    return send_file(fileobj.read(), mimetype='zip', as_attachment=True, attachment_filename = '%s.zip' % os.path.basename(FILEPATH)) 

app.run('0.0.0.0', 80)

client.py发送下载文件的请求:

^{pr2}$

server引发TypeError

TypeError: file() argument 1 must be encoded string without NULL bytes, not str

如何解决这个问题?在


Tags: pyioimportinfoappflaskservertime
1条回答
网友
1楼 · 发布于 2024-04-25 04:33:50

其中一个可能的解决方案将使用Flask.make_response方法:

from flask import Flask, request, send_file, make_response

@app.route('/download', methods=['GET','POST'])
def download():     
    fileobj = io.BytesIO()
    with zipfile.ZipFile(fileobj, 'w') as zip_file:
        zip_info = zipfile.ZipInfo(FILEPATH)
        zip_info.date_time = time.localtime(time.time())[:6]
        zip_info.compress_type = zipfile.ZIP_DEFLATED
        with open(FILEPATH, 'rb') as fd:
            zip_file.writestr(zip_info, fd.read())
    fileobj.seek(0)

    response = make_response(fileobj.read())
    response.headers.set('Content-Type', 'zip')
    response.headers.set('Content-Disposition', 'attachment', filename='%s.zip' % os.path.basename(FILEPATH))
    return response

相关问题 更多 >