Reputation: 53
i'v been looking for a solution for this issue for a week now, tried a lot of stuff nothing worked for me, I'm working on a project with react-native built on expo, what i'm trying to do is uploading an image using Imagepicker, i tried submitting it using axios and fetch, i'm able to send text data like (username, email ...) but can't send a file to the server, it doesn't recognise it a all, all it gives me is [object object], if any body was successful on doing that with php please share piece of your code, I did tried the backend with an html form and the file uploaded with no issues.
let picker = await ImagePicker.launchImageLibraryAsync({ base64: true });
const picker = selectedImage.base64;
This will return a base64 encoded image data, all you have to do is send it as a text field to the php server, decode it and put it into a file like this:
file_put_contents("example.jpg", base64_decode($_POST['image']));
And yeah, it's working
Upvotes: 0
Views: 2314
Reputation: 1629
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.
Upvotes: 1
Reputation: 53
// 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.";
}
Upvotes: 0