flask 下载文件
生活随笔
收集整理的這篇文章主要介紹了
flask 下载文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
from flask import Flask, send_file, Response, send_from_directory
import ioapp = Flask(__name__)def file_send(file_path): # 發送大文件可以該方法with open(file_path, 'rb') as f:while 1:data = f.read(20 * 1024 * 1024) # 每次讀取20Mif not data:breakyield data@app.route("/download1")
def download1():return send_file('test.xlsx', as_attachment=True, attachment_filename='test.xlsx') # 或使用下行代碼# return send_from_directory('./', 'test.xlsx', as_attachment=True)@app.route("/download2")
def download2():with open('test.xlsx', 'rb') as f:stream = f.read()response = Response(stream, content_type='application/octet-stream')response.headers['Content-disposition'] = 'attachment; filename=test.xlsx'return response@app.route("/download3")
def download3():file = io.BytesIO() # 本地沒有文件,將內容寫入內存發送file.write("你好".encode('utf-8'))file.seek(0)return send_file(file, as_attachment=True, attachment_filename="hi.txt") # 用下面3行代碼也可# response = Response(file, content_type='application/octet-stream')# response.headers['Content-disposition'] = 'attachment; filename=test.xlsx'# return response@app.route("/download4")
def download4():file_name = "MEM3.mp4"response = Response(file_send(file_name), content_type='application/octet-stream')response.headers["Content-disposition"] = f'attachment; filename={file_name}'return responseif __name__ == '__main__':app.run()
總結
以上是生活随笔為你收集整理的flask 下载文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 达梦数据库备份过程中的报错处理
- 下一篇: STM32F1 TCA9548A 驱动多