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应用程序以提高性能。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值