I wanted to upload file as input for FASTapi to process it. I tried running it in swagger and it works. However, I tried calling the api from my react native app in the phone but i can't seem to do it. I have been getting bad request error and I am not sure what should I passed as body or if the way I am calling is even correct since this is my first time dealing with API. How to correctly called api which accept file input? The image is what the input I am supposed to parsed in according to swagger. I have also added the log for heroku and the error I am getting from React Native.
React Native Code
const getImg = async imageUrl => {
const response = await fetch(imageUrl);
const imageBlob = await response.blob();
const reader = new FileReader();
reader.readAsDataURL(imageBlob);
reader.onloadend = () => {
const base64data = reader.result;
setImgUrl(base64data);
};
};
const chooseFromLibrary = () => {
ImagePicker.openPicker({
width: 300,
height: 400,
cropping: false,
}).then(image => {
console.log(image);
console.log(image['mime']);
getImg(image.path);
hi();
});
};
const hi = async () => {
let response = await fetch(
'https://receipt-ocr-heroku.herokuapp.com/receiptOcr',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: JSON.stringify({
file: imgUrl,
}),
},
);
console.log(response);
let result = await response.json();
console.log(result);
};
FastAPI Python
@app.post("/receiptOcr")
async def main(file: UploadFile = File(...)):
try:
image = await file.read()
# image = cv2.imread(image)
nparr = np.fromstring(image, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)