React-dropzone-uploader : 422 Unprocessable Entity with fastapi upload

Viewed 134

We are using react dropzone uploader to upload video with fastapi's

UploadFile

function

Below is the code

const MyUploader = () => {
  
  
  // called every time a file's `status` changes
  const handleChangeStatus = ({ meta, file }, status) => { console.log(status, meta, file) }
  
  // receives array of files that are done uploading when submit button is clicked
  const handleSubmit = (files, allFiles) => {
        files.map(file => uploadFile(file))
   
  }

  return (
    <Dropzone
      onChangeStatus={handleChangeStatus}
      onSubmit={handleSubmit}
      accept="video/*"
    />
  )
}

and

function uploadFile (file) {
  // Initial FormData
  console.log("file inside uploadfile",file)
  let formData = new FormData();
  formData.append("file_obj", file);
  const clientid=localStorage.getItem("client_id");
  console.log("clientid",clientid)

  return axios.post(`${apiEndpoint}/upload?clientId=${clientid}`, formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
}

below is the error getting

error.png

and backend code is

@router.post("/upload")
async def Videoupload(response: Response, clientId: str = None, file_obj: UploadFile = File(...)):
    try:
        if validate_filename(file_obj.filename):
              response.status_code=409 
              return "video with filename already exists"
        upload_video(clientId,file_obj)
        response.status_code = 201
        return "file uploaded"
    except Exception as error:
        print("Error in uploading", str(error))
        response.status_code = 500
        return "Error in uploading"

It could be great if anybody can help with this

1 Answers

Correct way of using RDU is to call upload api in

getUploadParams

const MyUploader = () => {
  const getUploadParams = ({ file, meta }) => {
    const body= new FormData()
    body.append('file_obj', file)
    const clientid=localStorage.getItem("client_id");
    console.log("clientid",clientid)
    return { url: `${apiEndpoint}/upload?clientId=${clientid}`, body }
}
  
  // called every time a file's `status` changes
  const handleChangeStatus = ({ meta, file }, status) => { console.log(status, meta, file) }
  
  // receives array of files that are done uploading when submit button is clicked
  const handleSubmit = (files, allFiles) => {
        console.log(files.map(f => f.meta))
        allFiles.forEach(f => f.remove())
   
  }

  return (
    <Dropzone
       getUploadParams={getUploadParams}
      onChangeStatus={handleChangeStatus}
      onSubmit={handleSubmit}
      accept="video/*"
    />
  )
}

Related