1

I am getting a HTTP 422 when attempting to upload a file from an Angular v13 application to FastAPI. I got great search results in a few different places 1, 2, 3, 4. However none of the solutions worked.

The FastAPI backend code/method as the following signature.

@router.post('/v1/file')
async def create_file(request: Request, file: UploadFile = File(...)):
    ...

The Angular code looks like the following.

fileSelected($event: any) {
  const file: File = $event.target.files[0];
  const data = new FormData();
  data.append('file', file, file.name);

  this.http.post<any>('http://localhost:8000/v1/file', data).subscribe({
    next: r => console.log(r),
    error: e => console.error(e)
  })
}

But I am still getting the following error: POST http://localhost:8000/v1/file 422 (Unprocessable Entity).

The HttpErrorResponse shows the following information

  • error.detail[0].loc = ['body', 'file']
  • error.detail[0].msg = 'field required'
  • error.detail[0].type = 'value_error.missing'

Any ideas on what I am doing wrong?

Jane Wayne
  • 8,205
  • 17
  • 75
  • 120
  • Try removing the default for `file` in your fastapi endpoint [(source)](https://fastapi.tiangolo.com/tutorial/request-files/#file-parameters-with-uploadfile) – crissal Jun 15 '22 at 19:37
  • @crissal When I do that, error.detail[0].loc is changed to `['query', 'file']`. – Jane Wayne Jun 15 '22 at 19:49
  • What happens with only `data.append('file', file);` (i.e. no `filename`) ? – lsabi Jun 15 '22 at 20:22
  • What happens if you do this: 1) remove the parameter ```request: Request```, 2) edit the second parameter to ```file: UploadFile = File(..., alias="file")``` – elano7 Jun 15 '22 at 21:49
  • What does the actual request being sent look like? (i.e. what does your browser's debug tools show as the actual request?) Make sure that the content is being sent as multipart/form-data and not as JSON (even if you're creating formdata, make sure that the library you're `post`-ing with sends it in the correct format) – MatsLindh Jun 15 '22 at 22:14

1 Answers1

1

This solved my issue (I'd spent the best part of half a day looking for a solution before finding this post)

  1. edit the second parameter to file: UploadFile = File(..., alias="file") – @elano7

and if you want to upload multiple files then

files: : List[UploadFile] = File(..., alias="files"

and then in the Angular file

onChange(event: any) {
    const files: FileList = event.target.files;
    const data = new FormData();
    for (let i = 0; i < files.length; i++) {
      data.append('files', files[i], files[i].name);
    }
    // move to on submit and then into data-storage
    this.http.post<any>('http://localhost:8000/file/upload', data).subscribe({
      next: r => console.log(r),
      error: e => console.error(e)
    })
  }
Pete
  • 11
  • 3