1

I have this example backend in Fastapi:

@router.post("/api/v1/upload")
def upload_file(file: UploadFile = File(...)):
    print(file)
    return 200

In the frontend I am not able to post the image successfully getting all the time 422 Unprocessable Entity.

<form @submit.prevent="handleUpload" class="space-y-6" >
   <div>
      <input type="file"  @change="handleFileInputChange" accept="image/jpeg, image/png, 
      image/jpg">
   </div>
<button type="submit">UPLOAD</button>

Script

async function  handleFileInputChange (event) {
        const formData = new FormData();
        formData.append("file", event.target.files[0])

and the POST part

async function handleUpload() {   
  
      const url = "http://0.0.0.0:8000/api/v1/upload"
      const requestOptions = {
            method: "POST",
            headers: {     
                'Content-Type': 'multipart/form-data'
            },
            body: { file: formdata.file },
                        
              
              
        }
        const data = await $fetch(url, requestOptions)

This is not working I have tried all options of Headers like 'Accept': '/','Content-Type': 'undefined',

I have tried this as well:

body: JSON.stringify({file: formdata.file})

Any help here? Probably is something fundamental that I am missing.

  • what the heck is `$fetch` - and is `http://0.0.0.0:8000/api/v1/upload` actually the url you're using? – Jaromanda X Jun 10 '23 at 09:51
  • 1
    This question has answers [here](https://stackoverflow.com/a/70824288/17865804), as well as [here](https://stackoverflow.com/a/72029319/17865804) and [here](https://stackoverflow.com/a/70689003/17865804) – Chris Jun 10 '23 at 10:01
  • Please have a look at [this answer](https://stackoverflow.com/a/75041731/17865804) as well, regarding the IP address `0.0.0.0` – Chris Jun 10 '23 at 10:04
  • No this is not the issue, i have tried this (0.0.0.0) – Nikolaos Epitropakis Jun 10 '23 at 10:22
  • Please do check followings. 1) Is your api working on postman? 2) If yes, on browser, is there any CORS issue? 3) Check with headers or changing MIME type to media. – Amad Jun 10 '23 at 10:30
  • Option 1 of [this answer](https://stackoverflow.com/a/70689003/17865804) provides a working example for you. As demonstrated in that example, you should **not** set the `Content-Type` header when sending `multipart/form-data`. Please have a look at the following answers for more details: [here](https://stackoverflow.com/a/74507628/17865804) and [here](https://stackoverflow.com/a/71711008/17865804) – Chris Jun 10 '23 at 11:22

0 Answers0