How can I upload a photo with Expo?
For to who’s not find or solved this issue. I spend three days to find solution and I got it. In my case it was a naming elements of data object. Android version 10, expo 4.11.0,
this is front
async function uploadImage(uploadFile){
const data = new FormData()
data.append('name',{
name: image_name, {/* name your image whatever you want*/}
type: 'image/jpeg', {/* type of image that you're uploading*/}
uri: uploadFile {/*data, file or image from ImagePicker here you should pass uri data but not all data from ImagePicker*/}
})
{/*names of data object should be like this: name, type, uri*/}
const response = await fetch(my_upload_api.php,{
method: 'POST',
body: data,
headers: {
'Content-Type': 'multipart/form-data'
}
})
}
this is backend on PHP
if(!empty($_FILES['name']['name'])){
$target_dir = 'my folder where I put all images';
if(!file_exists($target_dir)){
$data = array(
(object)array(
'code' => '400',
'message' => 'Can\'t fined folder.'
)
);
$json = json_encode($data);
echo $json;
die();
}
$target_file = $target_dir . basename($_FILES['name']['name']);
$image_file_type = pathinfo($target_file,PATHINFO_EXTENSION);
if(file_exists($target_file)){
$data = array(
(object)array(
'code' => '400',
'message' => 'Sorry. File already exists.'
)
);
$json = json_encode($data);
echo $json;
die();
}
if($_FILES['name']['size'] > 50000000){
$data = array(
(object)array(
'code' => '400',
'message' => 'Sorry. Your file is too large.'
)
);
$json = json_encode($data);
echo $json;
die();
}
if(move_uploaded_file($_FILES['name']['tmp_name'], $target_file)){
$data = array(
(object)array(
'code' => '200',
'message' => 'Successfuly your file has been uploaded.',
'name' => $_FILES['name']
)
);
$json = json_encode($data);
echo $json;
die();
}else{
$data = array(
(object)array(
'code' => '400',
'message' => 'Sorry. There was something wrong. Try it again.'
)
);
$json = json_encode($data);
echo $json;
die();
}
}
It was my first blog where I was trying to find solution. If solution was here I perhaps spend one or less days to solve this issue. I hope I can help someone.