import React, { useState } from 'react';
import { View, Button, Text, Alert } from 'react-native';
import { launchImageLibrary } from 'react-native-image-picker';
import axios from 'axios';
import { useThemeContext } from "../contexts/ThemeContext";
const SingleFileUploader = () => {
const [file, setFile] = useState(null);
const handleFileChange = () => {
launchImageLibrary(
{ mediaType: 'photo', includeBase64: false },
(response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.errorCode) {
console.log('ImagePicker Error: ', response.errorMessage);
Alert.alert('Hata', `Resim seçimi sırasında bir hata oluştu: ${response.errorMessage}`);
} else {
const selectedFile = response.assets[0];
setFile({
uri: selectedFile.uri,
type: selectedFile.type,
name: selectedFile.fileName,
});
}
},
);
};
const handleUpload = async () => {
if (file) {
console.log('Uploading file...');
console.log('Selected file:', file);
const formData = new FormData();
formData.append('comment', 'This is a test comment');
formData.append('rate', '5');
formData.append('machine_id', '1');
// Blob nesnesi oluştur
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
resolve(xhr.response);
};
xhr.onerror = function() {
reject(new Error('Failed to convert URI to Blob'));
};
xhr.responseType = 'blob';
xhr.open('GET', file.uri, true);
xhr.send(null);
});
formData.append('images[]', blob, file.name);
// FormData'nın içeriğini kontrol et
for (let pair of formData.entries()) {
console.log(pair[0] + ': ' + pair[1]);
}
try {
const response = await axios.post('https:///api/comments', formData, {
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer 108|',
},
});
console.log('Server response:', response.data);
if (response.data.image_urls && response.data.image_urls.length > 0) {
Alert.alert('Success', 'Resim başarıyla yüklendi!');
} else {
Alert.alert('Error', 'Resim yüklenemedi, lütfen tekrar deneyin.');
}
} catch (error) {
console.error('Error uploading file:', error);
if (error.response) {
console.error('Response data:', error.response.data);
console.error('Response status:', error.response.status);
console.error('Response headers:', error.response.headers);
Alert.alert('Hata', `Hata Detayları: ${error.response.data.message || error.response.data}`);
} else if (error.request) {
console.error('Request data:', error.request);
Alert.alert('Hata', 'Sunucuya ulaşılamıyor veya yanıt alınamıyor.');
} else {
console.error('Error message:', error.message);
Alert.alert('Hata', `Resim yüklenirken bir hata oluştu: ${error.message}`);
}
}
} else {
Alert.alert('Uyarı', 'Lütfen bir dosya seçin.');
}
};
return (
<View style={{ padding: 20 }}>
<Button title="Choose a file" onPress={handleFileChange} />
{file && (
<View>
<Text>File details:</Text>
<Text>Name: {file.name}</Text>
<Text>Type: {file.type}</Text>
</View>
)}
{file && <Button title="Upload a file" onPress={handleUpload} />}
</View>
);
};
export const HomeScreen = () => {
const { theme } = useThemeContext();
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: theme.colors.background }}>
<Text style={{ color: theme.colors.text }}>Welcome to React Native!</Text>
<SingleFileUploader />
</View>
);
};
Bu şekilde çözdüm gençler React Native için.