You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在FastAPI文件上传时通过HTML复选框传递可选参数?

实现带可选参数的音频上传分析功能

下面分步骤修正你的代码,实现上传音频并根据勾选的参数进行分析的功能:

一、更新前端HTML表单

先把表单里的复选框改成你需要的speech、music、noise选项,确保每个复选框的name属性和后端接收的参数名一致:

<!DOCTYPE html>
<html>
    <head>
        <title>音频分析工具</title>
        <link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet">
    </head>
    <body>
        <h1>音频分段分析</h1>
        <form method="POST" enctype="multipart/form-data" action="/submitform">
            <label>选择音频文件:</label>
            <input type="file" name="file" accept="audio/*"><br><br>
            
            <label>选择需要分析的内容:</label><br>
            <input type="checkbox" id="speech" name="speech" value="True">
            <label for="speech">语音</label><br>
            
            <input type="checkbox" id="music" name="music" value="True">
            <label for="music">音乐</label><br>
            
            <input type="checkbox" id="noise" name="noise" value="True">
            <label for="noise">噪音</label><br><br>
            
            <input type="submit" value="开始分析">
        </form>
    </body>
</html>
  • 新增accept="audio/*"限制仅上传音频文件
  • 给每个复选框添加对应标签,提升易用性
  • 明确表单提交的目标接口action="/submitform"

二、修正FastAPI后端逻辑

调整接口参数接收逻辑,处理上传的音频文件和勾选的分析参数,同时修复原代码中的错误:

from fastapi import FastAPI, Request, Form, File, UploadFile
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
import pandas as pd
from your_segmenter_module import Segmenter  # 替换成你的Segmenter实际导入路径
import tempfile
import os

app = FastAPI()
templates = Jinja2Templates(directory="template")

@app.get('/home/{user_name}', response_class=HTMLResponse)
def write_home(request: Request, user_name: str):
    return templates.TemplateResponse("basic_form.html", {"request": request, "username": user_name})

@app.post("/submitform")
async def handle_form(
    speech: bool = Form(False),
    music: bool = Form(False),
    noise: bool = Form(False),
    file: UploadFile = File(...)
):
    try:
        # 临时保存上传的音频文件(Segmenter通常需要文件路径)
        with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.filename)[1]) as temp_file:
            temp_file.write(await file.read())
            temp_file_path = temp_file.name
        
        # 执行音频分段分析
        seg = Segmenter()
        segmentation = seg(temp_file_path)
        segmentation_df = pd.DataFrame.from_records(segmentation, columns=['labels', 'start', 'stop'])
        
        # 根据勾选的参数过滤结果
        filtered_labels = []
        if speech:
            filtered_labels.append('speech')
        if music:
            filtered_labels.append('music')
        if noise:
            filtered_labels.append('noise')
        
        # 无勾选参数时返回全部结果,否则返回过滤后内容
        if filtered_labels:
            result_df = segmentation_df[segmentation_df['labels'].isin(filtered_labels)]
        else:
            result_df = segmentation_df
        
        # 清理临时文件
        os.unlink(temp_file_path)
        
        return HTMLResponse(content=result_df.to_html(index=False), status_code=200)
    
    except Exception as e:
        # 异常时确保清理临时文件
        if 'temp_file_path' in locals():
            os.unlink(temp_file_path)
        return HTMLResponse(content=f"<h3>分析失败</h3><p>错误信息:{str(e)}</p>", status_code=400)

主要修改点:

  1. 参数接收:新增speech、music、noise三个表单参数,默认值为False,与前端复选框name严格对齐
  2. 音频处理:用临时文件保存上传的音频内容,避免直接使用文件名(上传文件仅存在于内存,filename不是本地路径)
  3. 结果过滤:根据勾选参数过滤分析结果,返回用户需要的内容
  4. 异常修复:添加临时文件清理逻辑,修正异常返回的HTML格式(原代码返回字典会触发报错)

三、关键注意事项

  • 确保Segmenter类可接收文件路径作为输入,返回包含labels、start、stop的列表
  • 表单必须设置enctype="multipart/form-data"才能正确上传文件
  • 复选框未勾选时,后端自动使用默认值False,无需额外判断参数是否存在

内容的提问来源于stack exchange,提问作者rainbow12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 12:01:01