1

I am trying to upload an image from React Native and send it to FastAPI backend. The frontend code is like this:

//Image setting state
const [image, setImage] = useState(null);

//Picking image from the gallery
 const pickImage = async () => {
    const result = await launchImageLibrary({
      mediaType: 'photo',
    });
    console.log(result);
    setImage(result);
    if (result.didCancel === undefined) {
      dispatchFormState({
        type: 'INPUT_UPDATE',
        key: 'image',
        value: result.assets[0].uri,
      });
    }
  };

//Setting the formdata for sending image
 var formData = new FormData();
 formData.append('image', image.assets[0]); 
// image.assets[0] = {"fileName": "rn_image_picker_lib_temp_026efdef-fef2-496e-adbe-a6aee78b0ee6.jpg", "fileSize": 172658, "height": 1736, "type": "image/jpeg", "uri": "file:///data/user/0/com.thebeautifulmenu/cache/rn_image_picker_lib_temp_026efdef-fef2-496e-adbe-a6aee78b0ee6.jpg", "width": 1280}

In the backend, I am receiving the file like this:

@router.post("/", response_description="Create a new item", status_code=status.HTTP_201_CREATED)
def create_item(image: UploadFile = File(...)):
    # do something with the image
    return {"response": "image processed"}

This is throwing a 422 unprocessable entity error. What is the right way to send a file as a file object to the backend from React native?

Chris
  • 18,724
  • 6
  • 46
  • 80
akilesh raj
  • 656
  • 1
  • 8
  • 19
  • 1
    The 422 response body will contain an error message about which field(s) is missing or doesn’t match the expected format. Please have a look at related answers on how to upload files [here](https://stackoverflow.com/a/71311730/17865804), [here](https://stackoverflow.com/a/72029319/17865804), as well as [here](https://stackoverflow.com/a/70824288/17865804) and [here](https://stackoverflow.com/a/70640522/17865804). – Chris Oct 22 '22 at 06:16
  • Android or iOS or both? – user18309290 Oct 22 '22 at 08:26

0 Answers0