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

View File

@@ -6,15 +6,43 @@ export async function listLocations() {
try {
const response = await axios.get(`${API_URL}/locations/all`);
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) {
console.error("Error fetching locations:", 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) {
try {
const location = await axios.get(`${API_URL}/locations/${id}`);
@@ -22,7 +50,7 @@ export async function getLocation(id) {
throw new Error("Location not found");
}
return location.data;
return [...location.data, {image: normalizeImageSource(location.image)}];
} catch (error) {
console.error("Error fetching location:", error);
throw error;

View File

@@ -1,13 +1,14 @@
import { useState } from "react";
import {useState} from "react";
import {
StyleSheet,
Platform,
KeyboardAvoidingView,
ScrollView,
Image,
View,
} from "react-native";
import { TextInput, Button, Snackbar } from "react-native-paper";
import { requestCameraPermissionsAsync, launchCameraAsync } from 'expo-image-picker';
import {TextInput, Button, Snackbar, Text} from "react-native-paper";
import {requestCameraPermissionsAsync, launchCameraAsync} from 'expo-image-picker';
import useLocationStore from "@/locationStore";
export default function FormScreen() {
@@ -21,6 +22,7 @@ export default function FormScreen() {
const [message, setMessage] = useState("");
const [visible, setVisible] = useState(false);
const [picture, setPicture] = useState(null);
const [imageMethod, setImageMethod] = useState(null); // null, 'link' или 'camera'
const addLocation = useLocationStore((state) => state.addLocation);
@@ -49,6 +51,9 @@ export default function FormScreen() {
area: 0,
population: 0,
});
setPicture(null);
setImageMethod(null);
if (added != null) {
setMessage("Lokalizacja została dodana!");
setVisible(true);
@@ -58,6 +63,7 @@ export default function FormScreen() {
}
} else {
setMessage("Wypełnij wszystkie pola!");
console.log(formData);
setVisible(true);
}
};
@@ -65,20 +71,36 @@ export default function FormScreen() {
const takePicture = async () => {
const {status} = await requestCameraPermissionsAsync();
if (status !== 'granted') {
setMessage("Brak uprawnień do kamery!");
setVisible(true);
return;
}
const result = await launchCameraAsync({
allowsEditing: false,
base64: true,
});
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);
}
}
return (
<KeyboardAvoidingView
style={{ flex: 1 }}
style={{flex: 1}}
behavior={Platform.OS === "ios" ? "padding" : "height"}
>
<ScrollView contentContainerStyle={styles.container}>
@@ -89,67 +111,88 @@ export default function FormScreen() {
>
{message}
</Snackbar>
<TextInput
mode="outlined"
label="Nazwa"
placeholder="Wpisz nazwę"
style={{ margin: 10, width: "100%" }}
value={formData.name}
onChangeText={(e) => setFormData({ ...formData, name: e })}
/>
<TextInput
mode="outlined"
label="Opis"
placeholder="Wpisz opis"
style={{ margin: 10, width: "100%" }}
multiline={true}
value={formData.description}
onChangeText={(e) => setFormData({ ...formData, description: e })}
/>
<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%" }}
style={{margin: 10, width: "100%"}}
value={formData.image}
onChangeText={(e) => setFormData({ ...formData, image: e })}
onChangeText={(e) => setFormData({...formData, image: e})}
/>
)}
{picture && (
<View style={styles.imageContainer}>
<Image
source={{uri: picture}}
style={styles.image}
/>
</View>
)}
<TextInput
mode="outlined"
label="Nazwa"
placeholder="Wpisz nazwę"
style={{margin: 10, width: "100%"}}
value={formData.name}
onChangeText={(e) => setFormData({...formData, name: e})}
/>
<TextInput
mode="outlined"
label="Opis"
placeholder="Wpisz opis"
style={{margin: 10, width: "100%"}}
multiline={true}
value={formData.description}
onChangeText={(e) => setFormData({...formData, description: e})}
/>
<TextInput
mode="outlined"
label="Powierzchnia"
placeholder="Wpisz powierzchnię"
style={{ margin: 10, width: "100%" }}
style={{margin: 10, width: "100%"}}
value={formData.area}
keyboardType="numeric"
onChangeText={(e) => setFormData({ ...formData, area: e })}
onChangeText={(e) => setFormData({...formData, area: e})}
/>
<TextInput
mode="outlined"
label="Ludność"
placeholder="Wpisz liczbę ludności"
style={{ margin: 10, width: "100%" }}
style={{margin: 10, width: "100%"}}
value={formData.population}
keyboardType="numeric"
onChangeText={(e) => setFormData({ ...formData, population: e })}
onChangeText={(e) => setFormData({...formData, population: e})}
/>
<Button
style={{ margin: 10, width: "100%" }}
style={{margin: 10, width: "100%"}}
icon="plus-circle-outline"
mode={"contained"}
onPress={handleAddLocation}
>
Dodaj
</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>
</KeyboardAvoidingView>
);
@@ -161,12 +204,36 @@ const styles = StyleSheet.create({
backgroundColor: "#25292e",
justifyContent: "flex-start",
alignItems: "center",
padding: 10,
},
imageContainer: {
width: "100%",
alignItems: "flex-start",
marginVertical: 10,
},
image: {
width: 100,
height: 100,
width: 150,
height: 150,
borderStyle: "solid",
borderColor: "#fff",
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",
}
});

View File

@@ -22,7 +22,7 @@ export default function Index() {
<Card style={{ margin: 10 }}>
<Card.Cover
style={{ marginBottom: 10 }}
source={{ uri: item.image }}
source={item.imageSource}
/>
<Card.Content style={{ marginBottom: 10 }}>
<Text variant="titleLarge">{item.name}</Text>

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 { useTheme, Text, Card } from "react-native-paper";
import { useLocalSearchParams } from "expo-router";
@@ -33,7 +33,7 @@ export default function Location() {
<Card style={{ margin: 10 }}>
<Card.Cover
style={{ marginBottom: 10 }}
source={{ uri: location.image }}
source={location.imageSource}
/>
<Card.Content style={{ marginBottom: 10 }}>
<Text variant="headlineLarge" style={{ marginBottom: 10 }}>