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

React Native向FastAPI传视频报Axios错误:无法识别FormData部分

React Native 上传视频至FastAPI报错:Axios Network Error: Unrecognized FormData part

问题描述

React Native应用向FastAPI服务器上传视频时,持续触发Axios Network Error: Unrecognized FormData part错误。

前端代码

const uploadSelectedVideo = async ({
    selectedVideo,
  }: {
    selectedVideo: ImagePicker.ImagePickerAsset;
  }) => {
    const formData = new FormData();

    try {
      const response = await fetch(selectedVideo.uri);
      const videoBlob = await response.blob();
      
      // Append the video Blob to FormData
      formData.append("file", videoBlob, "video.mp4");
      const uploadResponse = await uploadVideo({ payload: formData });
      console.log("Video uploaded successfully:", uploadResponse.data);
    } catch (error) {
      console.error(`Error uploading video: ${error}`);
    }
  };

export const uploadVideo = async ({ payload }: { payload: FormData }) => {
  const response = await axios.post(
    `${ENV_VARS?.API_URL}/api/video/upload`,
    payload,
    {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    }
  );
  // Log the response status and data
  console.log("Response status:", response.status);
  console.log("Response data:", response.data);

  if (!response.data) {
    throw new Error("No response data provided");
  }
  return response.data;
};

后端代码

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.routes import video_routes

app = FastAPI()

app.include_router(video_routes.router)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
def read_root():
    return {"Hello": "World"}

@router.post("/api/video/upload")
async def upload_video_route(file: UploadFile = File(...)):
    try:
        return await upload_video(file)
    except HTTPException as e:
        raise HTTPException(status_code=500, detail="Error with file received")
    except Exception as e:
        logger.error(f"Unexpected error in upload_video_route: {str(e)}")
        raise HTTPException(status_code=500, detail="An unexpected error occurred")

前端FormData内容

{"_parts": [["file", [Blob]]]}

已尝试的排查步骤

  • 通过Postman和Swagger测试上传功能,均正常工作;
  • 移除请求头中的Content-Type设置,问题仍存在;
  • 调用其他接口确认React Native可正常访问服务器根路径;
  • Android端使用10.0.2.2地址访问服务器,问题依旧。

解决方案

1. 修正React Native中FormData的构建方式

React Native的FormData不直接支持Blob,需改用URI方式构造文件对象:

formData.append("file", {
  uri: selectedVideo.uri,
  name: "video.mp4",
  type: "video/mp4"
});

无需先通过fetch转换为Blob,直接使用原生文件URI构造FormData项即可。

2. 移除Axios请求头的Content-Type设置

Axios会自动根据FormData生成包含boundary的正确multipart/form-data请求头,手动设置会丢失boundary信息,导致后端无法解析。修改后的uploadVideo函数:

export const uploadVideo = async ({ payload }: { payload: FormData }) => {
  const response = await axios.post(
    `${ENV_VARS?.API_URL}/api/video/upload`,
    payload,
    {
      // 移除手动设置的Content-Type
      headers: {}
    }
  );
  console.log("Response status:", response.status);
  console.log("Response data:", response.data);

  if (!response.data) {
    throw new Error("No response data provided");
  }
  return response.data;
};

3. 验证Android端的URI格式

确保Android端的文件URI格式正确(如content://或file://开头),若为content://格式,React Native的FormData会自动处理适配。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 16:03:25