flask文件流下载

from flask import jsonify, json, request, make_response, Response, stream_with_context, send_file
import mimetypes

@api.route("/downloadFile/")
def downloadFile(filename):
    import os
    baseDir = os.path.join(os.getcwd(), "static")
    pathname = os.path.join(baseDir, filename)
    print pathname
    def send_chunk():  # 流式读取
        store_path = pathname
        with open(store_path, 'rb') as target_file:
            while True:
                chunk = target_file.read(20 * 1024 * 1024)  # 每次读取20M
                if not chunk:
                    break
                yield chunk
    return Response(send_chunk(), content_type='application/octet-stream')


@api.route("/downloadFile2/")
def downloadFile2(filename):
    import os
    baseDir = os.path.join(os.getcwd(), "static")
    pathname = os.path.join(baseDir, filename)
    f = open(pathname, "rb")
    response = Response(f.readlines())
    # response = make_response(f.read())
    mime_type = mimetypes.guess_type(filename)[0]
    response.headers['Content-Type'] = mime_type
    response.headers['Content-Disposition'] = 'attachment; filename={}'.format(filename.encode().decode('latin-1'))
    return response

你可能感兴趣的:(flask文件流下载)