I am getting uri from react-native-image-picker and I am storing the image data in an array then sending the images Array in in network call.
When I'm taking all images and save uri in state without cancelling the react-native-image-picker CameraActivity and sending all images through network call, that works perfectly.
But when I take one or more image and save uri in state, later if I open camera and go back from the react-native-image-picker cameraActivity without taking any picture, it gives me this error during network call:
Could not retrieve file for contentUri file:///storage/emulated/0/Pictures/images/image-e4da20e6-25a3-4e0f-a84c-d42ad9be7226.jpg
java.io.FileNotFoundException: /storage/emulated/0/Pictures/images/image-e4da20e6-25a3-4e0f-a84c-d42ad9be7226.jpg: open failed: ENOENT (No such file or directory)
at libcore.io.IoBridge.open(IoBridge.java:496)
at java.io.FileInputStream.<init>(FileInputStream.java:159)
This behaviour is really confusing to me.
I am using this function to take image and store it in state:
RNCamera()
.then(({ uri }) => {
setImages((prev) => [...prev, { uri: uri }]);
})
And I am sending request with the image object as FormData:
export const uploadFile = async (file: any, authToken?: any) => {
try{
const formData = new FormData();
formData.append('file', file);
let token = authToken;
if(!authToken) token = await AsyncStorage.getItem('userToken');
const res = await customFetch(FILE_UPLOAD_URL, {
method: "POST",
body: formData,
headers: {
'authorization': token ? `Bearer ${token}` : '',
}
});
if(!res.ok) throw new Error(res.statusText || `Error: Status is ${res.status}`)
return await res.json();
}catch(error: any){
throw new Error(error.message || "Error uploading file")
}
};
I am sending the file to uploadFile like this:
const fileIds = await Promise.all(images?.map(async img => {
const randomName = dateString + '_photo_' + Math.random() + ".jpg";
const file = {
uri: img.uri,
name: randomName,
type: 'image/jpg'
};
const res = await uploadFile(file, storeState?.userToken);
return res?.id
}))