当前位置:   article > 正文

Python Flask 文件下载_flask下载

flask下载

蓝图

  1. #!/usr/bin/python3
  2. # -*- coding: UTF-8 -*-
  3. # 文件下载接口
  4. import io
  5. from flask import Flask, url_for, request, render_template, redirect, flash, session, make_response,Blueprint, send_file, Response
  6. from flask_wtf.file import FileField, FileRequired, FileAllowed # 文件上传
  7. from flask import send_from_directory # 发送静态文件
  8. from flask_cors import CORS # 跨域访问
  9. from werkzeug.utils import secure_filename
  10. from werkzeug.routing import BaseConverter # 正则表达式
  11. import os,sys
  12. import uuid # 生成随机字符串
  13. import json
  14. from flask import current_app as app # 让蓝图可以使用app对象
  15. sys.path.append('../')
  16. from app.db import user # 导入用户模型
  17. # 创建蓝图对象
  18. downloadFile=Blueprint('downloadFile',__name__)
  19. def file_send(file_path): # 发送大文件可以该方法
  20. with open(file_path, 'rb') as f:
  21. while 1:
  22. data = f.read(20 * 1024 * 1024) # 每次读取20M
  23. if not data:
  24. break
  25. yield data
  26. '''
  27. [文件下载接口]
  28. '''
  29. @downloadFile.route('/download1', methods=['POST'])
  30. def download1():
  31. return send_file('test.xlsx', as_attachment=True, attachment_filename='test.xlsx') # 或使用下行代码
  32. # return send_from_directory('./', 'test.xlsx', as_attachment=True)
  33. @downloadFile.route("/download2")
  34. def download2():
  35. with open('test.xlsx', 'rb') as f:
  36. stream = f.read()
  37. response = Response(stream, content_type='application/octet-stream')
  38. response.headers['Content-disposition'] = 'attachment; filename=test.xlsx'
  39. return response
  40. @downloadFile.route("/download3")
  41. def download3():
  42. file = io.BytesIO() # 本地没有文件,将内容写入内存发送
  43. file.write("你好".encode('utf-8'))
  44. file.seek(0)
  45. return send_file(file, as_attachment=True, attachment_filename="hi.txt") # 用下面3行代码也可
  46. # response = Response(file, content_type='application/octet-stream')
  47. # response.headers['Content-disposition'] = 'attachment; filename=test.xlsx'
  48. # return response
  49. @downloadFile.route("/download4")
  50. def download4():
  51. file_name = "MEM3.mp4"
  52. response = Response(file_send(file_name), content_type='application/octet-stream')
  53. response.headers["Content-disposition"] = f'attachment; filename={file_name}'
  54. return response
  55. @downloadFile.route('/list', methods=['POST'])
  56. def register_list_api():
  57. try:
  58. request_data = request.json
  59. print("request.json",request.json)
  60. # 查询数据库是否存在该用户,且密码是否正确
  61. print(type(user.select_user_page(request_data["page_num"],request_data["page_size"])))
  62. # 如果用户名已存在,则返回一个数据类型为字典的json数据,如果不存在,则返回None
  63. result=user.select_user_page(request_data["page_num"],request_data["page_size"])
  64. print("register list :",result)
  65. return dict(code=200, msg="success", data=result)
  66. except Exception as e:
  67. print(e)
  68. return {"msg": "fali", "code": 401, "data": e}
  69. if __name__ == '__main__':
  70. print("downloadFile")

非蓝图

  1. from flask import Flask, send_file, Response, send_from_directory
  2. import io
  3. app = Flask(__name__)
  4. def file_send(file_path): # 发送大文件可以该方法
  5. with open(file_path, 'rb') as f:
  6. while 1:
  7. data = f.read(20 * 1024 * 1024) # 每次读取20M
  8. if not data:
  9. break
  10. yield data
  11. @app.route("/download1")
  12. def download1():
  13. return send_file('test.xlsx', as_attachment=True, attachment_filename='test.xlsx') # 或使用下行代码
  14. # return send_from_directory('./', 'test.xlsx', as_attachment=True)
  15. @app.route("/download2")
  16. def download2():
  17. with open('test.xlsx', 'rb') as f:
  18. stream = f.read()
  19. response = Response(stream, content_type='application/octet-stream')
  20. response.headers['Content-disposition'] = 'attachment; filename=test.xlsx'
  21. return response
  22. @app.route("/download3")
  23. def download3():
  24. file = io.BytesIO() # 本地没有文件,将内容写入内存发送
  25. file.write("你好".encode('utf-8'))
  26. file.seek(0)
  27. return send_file(file, as_attachment=True, attachment_filename="hi.txt") # 用下面3行代码也可
  28. # response = Response(file, content_type='application/octet-stream')
  29. # response.headers['Content-disposition'] = 'attachment; filename=test.xlsx'
  30. # return response
  31. @app.route("/download4")
  32. def download4():
  33. file_name = "MEM3.mp4"
  34. response = Response(file_send(file_name), content_type='application/octet-stream')
  35. response.headers["Content-disposition"] = f'attachment; filename={file_name}'
  36. return response
  37. if __name__ == '__main__':
  38. app.run()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/474592
推荐阅读
相关标签
  

闽ICP备14008679号