Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading