flask:文件下载send_from_directory

flask.send_from_directory(directory,filename,** options )

  1. directory –所有文件的存储目录。
  2. filename –相对于要下载的目录的文件名。
  3. options –直接转发到的可选关键字参数send_file()。
from flask import send_from_directory
@app.route('/download/<path:path>', methods=['GET', 'POST'])
def index(path):
    try:
        if os.path.isdir(filePath):
            return '<h1>文件夹无法下载</h1>'
        else:
            name=filePath.split('\\')[-1]#切割出文件名称
            filePath=filePath.replace(name,'')
            return send_from_directory(filePath,filename=name,as_attachment=True)
    except:
        return '<h1>该文件不存在或无法下载</h1>'

filePath:文件的绝对路径,不包含文件名
filename:文件名称
as_attachment:是否显示文件名称as_attachment –设置为True是否要发送带有标题的文件。Content-Disposition: attachment 如果设置为False则浏览器返回文件预览 如果该文件可以被浏览器渲染,例如 pdf 图片 等
notice:

  • 传入参数path必须为绝对路径
  • 若path所指文件不存在,不会有任何返回数据,造成用户体验下降
  • 若path所指文件不存在,可用404装饰器返回错误,或则用try语句包裹

点我直达官方文档

流式下载

@app.route('/download/<filename>')
def uploaded_file(filename):
    def send_file():
        store_path = os.path.join(UPLOAD_FOLDER,filename)
        with open(store_path, 'rb') as targetfile:
            while 1:
                data = targetfile.read(1 * 1024 * 1024)   # 每次读取1MB (可用限速)
                if not data:
                    break
                yield data
    response = Response(send_file(), content_type='application/octet-stream')
    response.headers["Content-disposition"] = 'attachment; filename=%s' % filename   # 如果不加上这行代码,导致下图的问题
    return response

发送文件和性能
强烈建议激活X-Sendfile您的Web服务器中的支持或(如果没有进行身份验证)告诉Web服务器自行为给定路径提供文件,而无需调用Web应用程序以提高性能。

  • 15
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Flask 中,`send_from_directory` 和 `send_file` 都用于向客户端文件,但有一些区别。 send_from_directory` 函数用于从指定目录中发送文件。它提供了方便的方式来发送静态文件,如图像、CSS、JavaScript 等。以下是一个示例代码: ```python from flask import Flask, send_from_directory app = Flask(__name__) @app.route('/images/<path:filename>') def get_image(filename): # 从指定目录中发送文件 return send_from_directory('static/images', filename) if __name__ == '__main__': app.run() ``` 在上面的示例中,当请求 `/images/filename.jpg` 时,`get_image` 函数会从 `static/images` 目录中发送名为 `filename.jpg` 的文件。 `send_file` 函数用于发送任意类型的文件。它可以发送动态生成的文件(如通过 Pandas 导出的 XLSX 文件),或者从任意路径中发送文件。以下是一个示例代码: ```python from flask import Flask, send_file import pandas as pd app = Flask(__name__) @app.route('/api/export') def export_data(): # 生成文件或从文件路径中获取文件 # ... # 发送文件 return send_file('path/to/file.xlsx', as_attachment=True) if __name__ == '__main__': app.run() ``` 在上面的示例中,当请求 `/api/export` 时,`export_data` 函数会发送名为 `file.xlsx` 的文件。 总结来说,`send_from_directory` 适用于发送静态文件,而 `send_file` 则适用于发送各种类型的文件,包括动态生成的文件。根据你的需求选择合适的函数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值