Flask用户选择文件夹视频播放功能异常求助
问题:选择视频后无法加载播放
以下是针对问题的具体修复方案:
1. 后端路由合并与数据传递修复
当前两个/AAR/路由会导致匹配冲突,且POST请求处理时未传递视频列表数据,导致提交后下拉框为空。
修复后后端代码:
@app.route('/AAR/', methods=['GET', 'POST']) def aar(): # 更安全的路径拼接,适配不同操作系统 path = Path().absolute() / "static" / "trainings" dirs = os.listdir(path) video_list = [{'name': dir} for dir in dirs] # 统一处理GET/POST请求的选中值:GET默认"hi",POST取表单提交值 selection = request.form.get('comp_select', "hi") return render_template('aar.html', data=video_list, selection=selection)
关键改进:
- 合并GET/POST请求到同一个路由函数,避免路由冲突
- 用路径对象拼接替代字符串拼接,避免跨平台路径问题
- 始终传递视频列表数据,保证下拉框在提交后依然有选项
2. 前端视频路径模板语法修复
原代码中视频src属性嵌套了Jinja模板语法,导致无法正确解析视频地址。
修复后视频区域代码:
<div id="load3" class="load3"> <h2>Video Replay Test</h2> <h2>{{ selection }}</h2> <video width=500 height="500" controls> {% if selection != "hi" %} <source src="{{ url_for('static', filename='trainings/' ~ selection)}}" type="video/mp4"> {% endif %} Your browser does not support the video tag. </video> </div>
关键改进:
- 使用Jinja字符串拼接符
~生成正确的静态文件路径,替代嵌套的模板语法 - 添加判断逻辑,避免初始状态下加载无效路径的视频
3. 前端体验优化(可选)
调整HTML结构规范,并让下拉框保持选中状态:
{% extends "header.html" %} {% block body %} <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href='/static/style.css' /> </head> <body> <center> <h1>Trainings</h1> <hr> <form class="form-inline" method="POST"> <div class="form-group"> <div class="input-group"> <span class="input-group-addon">Please select</span> <select name="comp_select" class="selectpicker form-control"> {% for o in data %} <option value="{{ o.name }}" {% if o.name == selection %}selected{% endif %}>{{ o.name }}</option> {% endfor %} </select> </div> <button type="submit" class="btn btn-default">Go</button> </div> </form> <hr> </center> <div id="load3" class="load3"> <h2>Video Replay Test</h2> <h2>{{ selection }}</h2> <video width=500 height="500" controls> {% if selection != "hi" %} <source src="{{ url_for('static', filename='trainings/' ~ selection)}}" type="video/mp4"> {% endif %} Your browser does not support the video tag. </video> </div> </body> {% endblock %}
额外优化:
- 将视频区域移入
<body>标签内,符合HTML规范 - 下拉框选项添加选中状态标记,提交后保持当前选择
内容的提问来源于stack exchange,提问作者Bob
相关产品推荐
相关产品推荐

