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?