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

Angular向FastAPI端点传递.wav Blob触发422(无法处理实体)错误

问题:Angular传递WAV Blob到FastAPI触发422错误

我在测试一个业务场景:将Angular录制的短音频.wav格式Blob传递至FastAPI端点进行后续处理,使用FastAPI的UploadFile选项实现时触发了422(Unprocessable Entity)错误,尝试直接将Blob作为POST参数传递也出现相同错误。

Angular代码

processRecording(blob:any) {
        const formData = new FormData();
        console.log("Form Data with audio file:",formData);
        formData.append('recording',blob);
        this.httpClient.post<any>("http://127.0.0.1:8000/postAudio",formData).subscribe(
          (response) => {
            console.log("Response received :", response);
          },
          (error) => {
            console.log("Error received :", error)
          }
}

Python(FastAPI)代码

@app.post("/postAudio")
async def postAudio(file:UploadFile = File(...)):
    print("Audio received!");
    return {'filename':file.filename}

问题原因及解决办法

  • 表单字段名不匹配:FastAPI定义的UploadFile参数名为file,但Angular中FormData.append使用的字段名是recording,字段名不一致导致后端无法识别上传的文件,这是422错误的核心原因。
  • Blob缺少文件名与MIME类型声明:直接传递Blob时,未指定文件名和音频的MIME类型(audio/wav),可能导致后端无法正确解析文件类型。

修改后的Angular代码(推荐FormData方式)

processRecording(blob: Blob) {
  const formData = new FormData();
  // 字段名与后端保持一致为'file',同时指定文件名和MIME类型
  formData.append('file', blob, 'recording.wav');
  this.httpClient.post<any>("http://127.0.0.1:8000/postAudio", formData, {
    headers: { 'Content-Type': undefined } // 让浏览器自动生成正确的multipart/form-data请求头
  }).subscribe(
    (response) => {
      console.log("Response received :", response);
    },
    (error) => {
      console.log("Error received :", error)
    }
  );
}

若需直接传递Blob的调整方案

后端代码修改

from fastapi import Body

@app.post("/postAudio")
async def postAudio(file: bytes = Body(...)):
    print("Audio received!");
    return {'status': 'success'}

Angular代码修改

processRecording(blob: Blob) {
  this.httpClient.post<any>("http://127.0.0.1:8000/postAudio", blob, {
    headers: { 'Content-Type': 'audio/wav' }
  }).subscribe(
    (response) => {
      console.log("Response received :", response);
    },
    (error) => {
      console.log("Error received :", error)
    }
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:55:16