Berikut ini contoh kode react-native-image-picker dan php
import React, { useState } from 'react';
import { View, Text, Button, Image, Alert } from 'react-native';
import ImagePicker from 'react-native-image-picker';
const App = () => {
const [imageSource, setImageSource] = useState(null);
const selectImage = () => {
ImagePicker.showImagePicker({ title: 'Select Image' }, (response) => {
if (!response.didCancel && !response.error) {
// Set the image source
setImageSource({ uri: response.uri });
uploadImage(response);
}
});
};
const uploadImage = async (image) => {
const formData = new FormData();
formData.append('file', {
uri: image.uri,
type: 'image/jpeg', // Sesuaikan dengan tipe file gambar yang didukung
name: 'image.jpg',
});
try {
const response = await fetch('https://example.com/server_upload.php', {
method: 'POST',
body: formData,
headers: {
'Content-Type': 'multipart/form-data',
},
});
if (response.ok) {
Alert.alert('Success', 'Image uploaded successfully');
} else {
Alert.alert('Error', 'Failed to upload image');
}
} catch (error) {
console.error('Error uploading image:', error);
}
};
return (
<View>
<Text>Image Upload Example</Text>
{imageSource && <Image source={imageSource} style={{ width: 200, height: 200 }} />}
<Button title="Select Image" onPress={selectImage} />
</View>
);
};
export default App;
Leave a Reply