I face a problem for uploading the image to cloudinary.The issue is that when i upload the image from my react native app its first change the image into base base 64 and send it into the backend but when the code reaches to the upload system its give the error errno: -4058,
code: ‘ENOENT’,
syscall: ‘open’,
I dont know why i upload the image from phone and this case occur that no path found so i sharre you all my code because i am dont understand why its happen.My credential of cloudinary are ok so there is no issue with cloudinary api .i could not mention it while sharing the code but you have to assume that the credential are ok because i have check it several time.
So lets start the sharing of code
Here is my reactnative component which have the form
import { View,Text,Button,StyleSheet,Image,KeyboardAvoidingView,Keyboard
} from "react-native";
import {Picker} from "@react-native-picker/picker"
import React from "react";
import { useNavigation } from "@react-navigation/native";
import { TextInput } from "react-native-gesture-handler";
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import {useDispatch,useSelector} from "react-redux"
import { RegisterClass,GetClassessInfo, addAdmin } from '../../actions/adminAction';
import { useState ,useEffect} from "react";
import * as ImagePicker from 'expo-image-picker';
import * as FileSystem from 'expo-file-system';
export default function ManageAdmin(){
const {isAuthenticated,admin}=useSelector((state)=>state.admin)
const [name,setname]=useState("");
const [email,setemail]=useState("");
const [phone,setphone]=useState("");
const [address,setaddress]=useState("");
const [password,setpassword]=useState("");
const [image, setImage] = useState(null);
const [avatar,setAvatar] =useState(null);
const navigation=useNavigation();
const dispatch=useDispatch();
console.log(admin);
// console.log("error");
//console.log(loading);
//console.log(isAuthenticated);
const AdminSubmit=async()=>{
dispatch(addAdmin(name,email,address,phone,password,image ))
}
useEffect(()=>{
if(isAuthenticated){
//console.log(user);
}
},[])
/*const handleImageSelect = async () => {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
return;
}
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [1, 1],
quality: 1,
});
if (!result.canceled) {
const selectedAsset = result.assets[0];
const base64Image = await FileSystem.readAsStringAsync(selectedAsset.uri, {
encoding: FileSystem.EncodingType.Base64,
});
setAvatar(result.uri);
setImage(base64Image);
// Use the base64Image as needed
console.log(base64Image);
const selectedAsset = result.assets[0];
setAvatar(result.uri);
setImage(selectedAsset.uri);
// Use the image URI as needed
console.log(selectedAsset.uri);
}
};*/
/*const handleImageSelect = async () => {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
return;
}
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [1, 1],
quality: 1,
});
if (!result.cancelled) {
const { uri } = result;
setAvatar(uri);
setImage(uri);
console.log(uri);
}
};
*/
const handleImageSelect = async () => {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
return;
}
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [1, 1],
quality: 1,
});
if (!result.canceled) {
const selectedAsset = result.assets[0];
const base64Image = await FileSystem.readAsStringAsync(selectedAsset.uri, {
encoding: FileSystem.EncodingType.Base64,
});
setAvatar(result.uri);
setImage(base64Image);
// Use the base64Image as needed
console.log(base64Image);
}
};
const convertImageToBase64 = async (imageUri) => {
try {
console.log(imageUri);
const base64 = await FileSystem.readAsStringAsync(imageUri, {
encoding: FileSystem.EncodingType.Base64,
});
return base64;
} catch (error) {
console.error('Error converting image to base64:', error);
return null;
}
};
return(
<View style={styles.Mainview}>
<View style={styles.Mvinnertwo}>
<View style={styles.Loginform}>
<View style={styles.Loginformfields}>
<TextInput style={styles.MvinneroneInputSearch} placeholder="name " value={name} onChangeText={text => setname(text)} ></TextInput>
<TextInput style={styles.MvinneroneInputSearch} placeholder="email" value={email} onChangeText={text => setemail(text)}></TextInput>
<TextInput style={styles.MvinneroneInputSearch} placeholder="phone" value={phone} onChangeText={text => setphone(text)}></TextInput>
<TextInput style={styles.MvinneroneInputSearch} placeholder="address" value={address} onChangeText={text => setaddress(text)} ></TextInput>
<TextInput style={styles.MvinneroneInputSearch} placeholder="password" value={password} onChangeText={text => setpassword(text)}></TextInput>
<Button title="Select Image" onPress={handleImageSelect} />
{avatar && <Image source={{ uri: avatar }} style={{ width: 200, height: 200 }} />}
</View>
<View style={styles.signIN}>
<View style={styles.signINbutton}>
<Button title="Add Admin" color="#7956b5"
onPress={AdminSubmit}
></Button>
</View>
<View style={styles.signUpbutton}>
<Button title="View All Classes" color="#7956b5" ></Button>
</View>
</View>
</View>
</View>
</View>
);
}
const styles = StyleSheet.create({
Mainview:{
height:"100%",
backgroundColor:"#7956b5",
alignItems:"center"
},
Mvinnerone:{
// flex:1,
height:"35%",
flexDirection:'column'
},
Mvinnerone1Image:{
marginLeft:-20,
alignItems:'flex-start',
width:150,
height:150
},
Mvinnerone1:{
flexDirection:'row'
},
Mvinnerone1view1:{
justifyContent:'center',
alignItems:'flex-start',
width:"30%",
},
Mvinnerone1view2:{
justifyContent:'center',
alignItems:'center',
width:"70%",
fontSize:20
},
Mvinnerone1view2Text:{
fontSize:20,
color:'white'
},
MvinneroneInput:{
justifyContent:'center',
alignItems:'center'
},
MvinneroneInputSearch:{
//justifyContent:'center',
//alignItems:'center',
marginTop:20,
backgroundColor:'white',
width:'100%',
padding:'2%',
borderColor:"#7956b5",
borderWidth:2,
borderRadius:10
},
Mvinnertwo: {
padding:"5%",
backgroundColor: "white",
width:"95%",
height:'100%',
borderColor:'white',
borderWidth:1,
borderRadius:20,
shadowColor:"black",
shadowOffset:2,
},
Row1:{
flexDirection:'row',
height:100,
justifyContent:'center',
},
cel1:{
justifyContent:"center",
alignItems:"center",
width:"25%",
margin:10,
borderColor:"#7956b5",
borderWidth:2,
borderRadius:10,
shadowColor:'#000',
shadowOffset:{width:0,height:7},
shadowOpacity:0.43,
shadowRadius:9.51
},
cel2:{
justifyContent:"center",
alignItems:"center",
width:"25%",
margin:10,
borderColor:"#7956b5",
borderWidth:2,
borderRadius:10
},
cel3:{
justifyContent:"center",
alignItems:"center",
width:"25%",
margin:10,
borderColor:"#7956b5",
borderWidth:2,
borderRadius:10
},
forgotpass:{
flexDirection:'row',
justifyContent:'flex-end',
marginTop:4,
marginBottom:4
},
signIN:{
marginTop:'2%',
justifyContent:"center"
},
signINbutton:{
marginBottom:6
},
Loginform:{
//alignItems:"center"
}
});
Here is the action which target the backend api
export const addAdmin = (name,email,phone,address,password,image) => async (dispatch) => {
try {
dispatch({ type: Add_Admin_Request });
// const config = { headers: { "Content-Type": "application/json" } };
console.log("yes");
console.log(image);
const { data } = await axios.post(
`http://192.168.100.42:4000/api/v1/RegisterAdmin`,
{ name,email,phone,address,password,image },
{
headers: {
"Content-Type": "multipart/form-data",
},
}
);
console.log("After Posting");
console.log(data);
dispatch({ type: Add_Admin_Success, payload: data.user });
} catch (error) {
if (error.response && error.response.data && error.response.data.message) {
dispatch({ type: Add_Admin_Fail, payload: error.response.data.message });
} else {
dispatch({ type: Add_Admin_Fail, payload: "An error occurred" });
}
}
};
Here is the reducer
export const adminProfileReducer=(state={admin:{}},action)=>{
switch(action.type){
case Get_AdminOWNPROFILE_REQUEST:
case Add_Admin_Request:
return{
loading:true,
isAuthenticated:false
};
case Get_AdminOWNPROFILE_SUCCESS:
case Add_Admin_Success:
return{
...state,
loading:false,
isAuthenticated:true,
//adminProfileInfo:action.payload
user:action.payload
};
case Get_AdminOWNPROFILE_FAIL:
case Add_Admin_Fail:
return{
...state,
loading:false,
isAuthenticated:false,
user:null,
error:action.payload
};
/*case CLEAR_ERRORS:
return{
...state,
error:null
};*/
default:{
return state;
}
}
}
Here is the backend which have the cloudinary system
exports.registerAdmin = catchAsyncError(async (req, res, next) => {
console.log("1");
cloudinary.config({
cloud_name: 'daequ7ofa',
api_key: '762768164935239',
api_secret: 'po-dxhHi3sYDqG4VvB32bDYANMg'
});
console.log(req.body.image);
try {
const result = await cloudinary.uploader.upload(req.body.image, {
folder: 'avatar'
});
console.log('Image uploaded to Cloudinary:', result);
const { public_id, secure_url } = result;
const { name, email, password, phone, address } = req.body;
const user = await admin.create({
name,
email,
password,
phone,
address,
image: {
public_id,
url: secure_url
}
});
console.log("Admin created:", user);
sendToken(user, 201, res);
} catch (error) {
console.error('Error uploading image to Cloudinary:', error);
next(error);
}
});
Please kindly check it and give the solution.