flask大文件下载解决方案

flask大文件下载解决方案

文件数据小的话,可以直接使用flask自带的send_file()
读取文件或者直接写入缓冲区,再去读取都可以,StringIO, ByteIO,这样就是能写成不生层本地文件去下载的模式了

@app.route('download')
def download():
    file_hash = request.args.get('file')
    if file_hash:
        file = File.by_hash(file_hash)
        path = os.path.join('./output', '{}.csv'.format(file.filename.split('.')[0]))
        def file_send():
            store_path = path
            with open(store_path, 'rb') as targetfile:
                while 1:
                    data = targetfile.read(20 * 1024 * 1024)  # 每次读取20M
                    if not data:
                        break
                    yield data

        response = Response(file_send(), content_type='application/octet-stream')
        response.headers["Content-disposition"] = 'attachment; filename=%s.csv' % file.filename.split('.')[0]  # 如果不加上这行代码,导致下图的问题
        return response

你可能感兴趣的:(python基础教程)