2

as the title says, I'm trying to upload a file from React front end to FastAPI. The code I used is below:

//this is backend FastAPI   ================== 
@app.post("/uploadfile")
async def create_upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename}

//frontend ===================================
const [file, uploadFile] = useState(null)

//when upload button clicked
function handleSubmit(){
    console.log(file[0].name)
    const formdata = new FormData();
    formdata.append(
      "file",
      file[0],
    )
    axios.post("/uploadfile", {
      file:formdata}, {
        "Content-Type": "multipart/form-data",
      })
          .then(function (response) {
            console.log(response); //"dear user, please check etc..."
          });
      
  }

// this is when file has been selected
  function handleChange(e){
    uploadFile(e.target.files); //store uploaded file in "file" variable with useState
  }

It returns a 422 (Unprocessable Entity). The message detail from axios is:

enter image description here

I am not quite familiar with the rules and format needed behind file uploading. Could someone clear my confusion?

KingJac
  • 94
  • 9
  • Related answers can be found [here](https://stackoverflow.com/a/72029319/17865804), as well as [here](https://stackoverflow.com/a/70689003/17865804) and [here](https://stackoverflow.com/a/74507628/17865804) – Chris Jul 27 '23 at 04:47

2 Answers2

0

Update from OP: I have managed to solve the problem by replacing the axios part with

const headers={'Content-Type': file[0].type}
await axios.post("/uploadfile",formdata,headers)
    .then()//etc

if anyone want to add more information on why that works please feel free to do so - since I'm not quite sure either.

KingJac
  • 94
  • 9
  • This was helpful for me. I think the key is ensuring that the key to the form data matches the `UploadFIle` parameter for you FastAPI endpoint. In this case the key is `file`. In the react code you have: formdata.append( "file", file[0], ) And in the Python code you have: ``` async def create_upload_file(file: UploadFile = File(...)): ``` – jsnow Jul 26 '23 at 20:22
0

This was helpful for me finding a bug in my code. I suspect your problem was nesting the formData inside another object in your first attempt: axios.post("/uploadfile", {file:formdata} ... should be axios.post("/uploadfile", formdata ....

For me, the trick was ensuring that the key to the formData.append exactly matches the name of the UploadFile parameter for my FastAPI endpoint.

In this example the name is file123.

In the React code you have:

formdata.append("file123", file[0])
axios.post("/uploadfile", formdata ...etc...

And in the Python code you have:

async def create_upload_file(file123: UploadFile = File(...)): ...etc...
jsnow
  • 1,399
  • 1
  • 9
  • 7