Upload a file from react-native (expo) project to a php server (laravel)
Solution:
the simplest solutions is to use the base64 image format.
You can set in the options bese64 to true:
let picker = await ImagePicker.launchImageLibraryAsync({ base64:true });
And append the value in a classic json object and avoid the multipar/fomr-data, just for php decode the base64 image.
Answer
Solution:
React native
// State variable to hold the picked image
const [selectedImage, setSelectedImage] = useState(false);
// Use image picker to choose a picture
let openImage = async () => {
let permission = await ImagePicker.requestCameraRollPermissionsAsync();
if (permission.granted == false) {
return;
}
let picker = await ImagePicker.launchImageLibraryAsync();
setSelectedImage(picker);
}
// Upload image to the server
const uploadimage = async () => {
const payload = new FormData();
payload.append('image', {
uri: selectedImage.uri,
type: selectedImage.type,
name: selectedImage.fileName
})
const config = {
body: payload,
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
}
};
let response = await fetch('http://192.168.1.6/php_upload/upload.php', config);
console.log(response);
}
// PHP Backend
$target_file = "uploads/" . basename($_FILES["image"]["name"]);
if ( move_uploaded_file($_FILES["photo"]["tmp_name"], $target_file) )
{
echo "The file ". basename( $_FILES["photo"]["name"]). " has been uploaded.";
}
else
{
echo "Sorry, there was an error uploading your file.";
}
Source