Wysyłanie zdjęć na backend i ich odbieranie

This commit is contained in:
2025-05-23 15:13:31 +02:00
parent c6fbbe9222
commit 0ee2b8d702
4 changed files with 258 additions and 163 deletions
+31 -3
View File
@@ -6,15 +6,43 @@ export async function listLocations() {
try { try {
const response = await axios.get(`${API_URL}/locations/all`); const response = await axios.get(`${API_URL}/locations/all`);
if (!response) { if (!response) {
throw new Error("No locations found"); return "No locations found";
} }
return response.data;
// Нормализуем изображения в полученных данных
return response.data.map(location => ({
...location,
imageSource: normalizeImageSource(location.image)
}));
} catch (error) { } catch (error) {
console.error("Error fetching locations:", error); console.error("Error fetching locations:", error);
throw error; throw error;
} }
} }
const normalizeImageSource = (image) => {
if (!image) return null;
// Проверка, является ли изображение URL
if (typeof image === 'string') {
// Если строка начинается с http или https, это URL
if (image.startsWith('http://') || image.startsWith('https://')) {
return { uri: image };
}
// Проверка на base64
if (image.startsWith('data:image')) {
return { uri: image };
} else if (image.length > 100) {
// Предполагаем, что это base64 без префикса
return { uri: `data:image/jpeg;base64,${image}` };
}
}
// Возвращаем null для неправильного формата
return null;
}
export async function getLocation(id) { export async function getLocation(id) {
try { try {
const location = await axios.get(`${API_URL}/locations/${id}`); const location = await axios.get(`${API_URL}/locations/${id}`);
@@ -22,7 +50,7 @@ export async function getLocation(id) {
throw new Error("Location not found"); throw new Error("Location not found");
} }
return location.data; return [...location.data, {image: normalizeImageSource(location.image)}];
} catch (error) { } catch (error) {
console.error("Error fetching location:", error); console.error("Error fetching location:", error);
throw error; throw error;
+89 -22
View File
@@ -5,8 +5,9 @@ import {
KeyboardAvoidingView, KeyboardAvoidingView,
ScrollView, ScrollView,
Image, Image,
View,
} from "react-native"; } from "react-native";
import { TextInput, Button, Snackbar } from "react-native-paper"; import {TextInput, Button, Snackbar, Text} from "react-native-paper";
import {requestCameraPermissionsAsync, launchCameraAsync} from 'expo-image-picker'; import {requestCameraPermissionsAsync, launchCameraAsync} from 'expo-image-picker';
import useLocationStore from "@/locationStore"; import useLocationStore from "@/locationStore";
@@ -21,6 +22,7 @@ export default function FormScreen() {
const [message, setMessage] = useState(""); const [message, setMessage] = useState("");
const [visible, setVisible] = useState(false); const [visible, setVisible] = useState(false);
const [picture, setPicture] = useState(null); const [picture, setPicture] = useState(null);
const [imageMethod, setImageMethod] = useState(null); // null, 'link' или 'camera'
const addLocation = useLocationStore((state) => state.addLocation); const addLocation = useLocationStore((state) => state.addLocation);
@@ -49,6 +51,9 @@ export default function FormScreen() {
area: 0, area: 0,
population: 0, population: 0,
}); });
setPicture(null);
setImageMethod(null);
if (added != null) { if (added != null) {
setMessage("Lokalizacja została dodana!"); setMessage("Lokalizacja została dodana!");
setVisible(true); setVisible(true);
@@ -58,6 +63,7 @@ export default function FormScreen() {
} }
} else { } else {
setMessage("Wypełnij wszystkie pola!"); setMessage("Wypełnij wszystkie pola!");
console.log(formData);
setVisible(true); setVisible(true);
} }
}; };
@@ -65,14 +71,30 @@ export default function FormScreen() {
const takePicture = async () => { const takePicture = async () => {
const {status} = await requestCameraPermissionsAsync(); const {status} = await requestCameraPermissionsAsync();
if (status !== 'granted') { if (status !== 'granted') {
setMessage("Brak uprawnień do kamery!");
setVisible(true);
return; return;
} }
const result = await launchCameraAsync({ const result = await launchCameraAsync({
allowsEditing: false, allowsEditing: false,
base64: true,
}); });
if (!result.canceled && result.assets && result.assets.length > 0) { if (!result.canceled && result.assets && result.assets.length > 0) {
setPicture(result.assets[0].uri); const image = result.assets[0];
setPicture(image.uri);
console.log(image.base64);
setFormData({...formData, image: image.base64});
}
}
const selectImageMethod = (method) => {
setImageMethod(method);
if (method === 'camera') {
takePicture()
} else {
setFormData({...formData, image: ""});
setPicture(null);
} }
} }
@@ -89,6 +111,45 @@ export default function FormScreen() {
> >
{message} {message}
</Snackbar> </Snackbar>
<Text style={styles.label} variant="labelLarge">Jak chcesz dodać zdjęcie?</Text>
<View style={styles.imageMethodButtons}>
<Button
mode={imageMethod === 'link' ? "contained" : "outlined"}
onPress={() => selectImageMethod('link')}
style={styles.methodButton}
>
Użyj linku
</Button>
<Button
mode={imageMethod === 'camera' ? "contained" : "outlined"}
onPress={() => selectImageMethod('camera')}
style={styles.methodButton}
>
Zrób zdjęcie
</Button>
</View>
{imageMethod === 'link' && (
<TextInput
mode="outlined"
label="Link do zdjęcia"
placeholder="Wpisz link do zdjęcia"
multiline={true}
style={{margin: 10, width: "100%"}}
value={formData.image}
onChangeText={(e) => setFormData({...formData, image: e})}
/>
)}
{picture && (
<View style={styles.imageContainer}>
<Image
source={{uri: picture}}
style={styles.image}
/>
</View>
)}
<TextInput <TextInput
mode="outlined" mode="outlined"
label="Nazwa" label="Nazwa"
@@ -106,15 +167,6 @@ export default function FormScreen() {
value={formData.description} value={formData.description}
onChangeText={(e) => setFormData({...formData, description: e})} onChangeText={(e) => setFormData({...formData, description: e})}
/> />
<TextInput
mode="outlined"
label="Link do zdjęcia"
placeholder="Wpisz link do zdjęcia"
multiline={true}
style={{ margin: 10, width: "100%" }}
value={formData.image}
onChangeText={(e) => setFormData({ ...formData, image: e })}
/>
<TextInput <TextInput
mode="outlined" mode="outlined"
label="Powierzchnia" label="Powierzchnia"
@@ -141,15 +193,6 @@ export default function FormScreen() {
> >
Dodaj Dodaj
</Button> </Button>
<Button onPress={takePicture} style={{ margin: 10, width: "100%" }} icon="plus-circle-outline" mode={"contained"}>
Zrób zdjęcie
</Button>
{picture && (
<Image
source={{ uri: picture.uri }}
style={styles.image}
/>
)}
</ScrollView> </ScrollView>
</KeyboardAvoidingView> </KeyboardAvoidingView>
); );
@@ -161,12 +204,36 @@ const styles = StyleSheet.create({
backgroundColor: "#25292e", backgroundColor: "#25292e",
justifyContent: "flex-start", justifyContent: "flex-start",
alignItems: "center", alignItems: "center",
padding: 10,
},
imageContainer: {
width: "100%",
alignItems: "flex-start",
marginVertical: 10,
}, },
image: { image: {
width: 100, width: 150,
height: 100, height: 150,
borderStyle: "solid", borderStyle: "solid",
borderColor: "#fff", borderColor: "#fff",
borderWidth: 1, borderWidth: 1,
borderRadius: 5,
}, },
imageMethodButtons: {
flexDirection: 'row',
justifyContent: 'space-between',
width: '100%',
marginVertical: 10,
},
methodButton: {
flex: 1,
marginHorizontal: 5,
},
label: {
marginTop: 10,
marginBottom: 10,
color: "#fff",
verticalAlign: "middle",
textAlign: "center",
}
}); });
+1 -1
View File
@@ -22,7 +22,7 @@ export default function Index() {
<Card style={{ margin: 10 }}> <Card style={{ margin: 10 }}>
<Card.Cover <Card.Cover
style={{ marginBottom: 10 }} style={{ marginBottom: 10 }}
source={{ uri: item.image }} source={item.imageSource}
/> />
<Card.Content style={{ marginBottom: 10 }}> <Card.Content style={{ marginBottom: 10 }}>
<Text variant="titleLarge">{item.name}</Text> <Text variant="titleLarge">{item.name}</Text>
+2 -2
View File
@@ -1,4 +1,4 @@
import { View, ScrollView, StyleSheet, ActivityIndicator } from "react-native"; import { View, ScrollView, StyleSheet } from "react-native";
import { useEffect } from "react"; import { useEffect } from "react";
import { useTheme, Text, Card } from "react-native-paper"; import { useTheme, Text, Card } from "react-native-paper";
import { useLocalSearchParams } from "expo-router"; import { useLocalSearchParams } from "expo-router";
@@ -33,7 +33,7 @@ export default function Location() {
<Card style={{ margin: 10 }}> <Card style={{ margin: 10 }}>
<Card.Cover <Card.Cover
style={{ marginBottom: 10 }} style={{ marginBottom: 10 }}
source={{ uri: location.image }} source={location.imageSource}
/> />
<Card.Content style={{ marginBottom: 10 }}> <Card.Content style={{ marginBottom: 10 }}>
<Text variant="headlineLarge" style={{ marginBottom: 10 }}> <Text variant="headlineLarge" style={{ marginBottom: 10 }}>