angularfastapihttpclient

Problem with sending FormData with HttpClient from Angular 18 to FastAPI


As described in the title I am trying to send a file via FormData from an Angular 18 Frontend to a FastAPI Backend.

My code in Angular:

  uploadFile(fileFormData: FormData) {
    const url: string = this.api_url;

    const body =
    {
      upload_file: fileFormData
    };

    return this.httpClient.post(url, body);
  }

My code in FastAPI:

@app.post("/upload")
async def upload(upload_file: UploadFile = File(...)):
    if upload_file:

        return status.HTTP_202_ACCEPTED

    else:
        raise HTTPException(status_code=status.HTTP_405_METHOD_NOT_ALLOWED)

This is the result when sending the API Request :

Status: 422 Unprocessable Content

Response details:
{"detail":[{"type":"missing","loc":["body","upload_file"],"msg":"Field required","input":null}]}

So according to the response details the problem should be clear but how to fix this? In my Angular code the apparently missing field "upload_file" is provided in the body for the post request, so that should be correct.

I already tried playing with the content type in header information but without luck.

Does anyone have an idea what I could do to get this fixed and running? Thank you very much in advance. Cheers

I already tried playing with the content type in header information but without luck.


Solution

  • Upload the file using FormData instead of sending it through the body as is.

    uploadFile(fileFormData: FormData) {
      const url: string = this.api_url;
      const fd = new FormData();
      fd.append('upload_file', this.selectedFile, this.selectedFile.name);
      return this.httpClient.post(url, fd);
    }
    

    Reference Stackblitz