Search code examples
react-nativefastapi

Uploading video from React Native to FastAPI causing "Axios Network Error: Unrecognized FormData part"


I'm trying to upload a video from my React Native app to my FastAPI server but I keep Axios Network Error: Unrecognized FormData part.

Frontend:

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;
};

Backend:

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")

This is what the frontend also holds within formData: {"_parts": [["file", [Blob]]]}

What I've tried so far:

  1. Testing via Postman and the Swagger docs. Both are working.
  2. Tried removing headers. Still not working.
  3. Tried calling other endpoints. I can verify my root endpoint is working on React Native.
  4. Testing on Android and I'm already using 10.0.2.2

Solution

  • Instead of blob try passing this in form data:

    formData.append('file', {
              uri: selectedVideo.uri,
              type: selectedVideo.type,
              name: selectedVideo.fileName,
            });