import React, { useState } from "react";
import { Button, Image, SafeAreaView, View } from "react-native";
import * as ImagePicker from "expo-image-picker";
import { Client, ID, Storage } from "appwrite";
const client = new Client();
client
.setEndpoint(MY_ENDPOINT)
.setProject(MY_PROJECT_ID);
const bucketId = MY_BUCKET_ID;
const filesStorage = new Storage(client);
export default function ImagePickerScreen() {
const [image, setImage] = useState(null);
const uploadFile = async (file) => {
return filesStorage.createFile(file, ID.unique());
};
const pickImage = async () => {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== "granted") {
console.log("Permission denied!");
return;
}
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
quality: 1,
});
if (!result.canceled) {
setImage(result.assets[0].uri);
}
};
const handleUploadFile = async () => {
if (!image) {
console.log("No image selected!");
return;
}
try {
const response = await fetch(image);
const blob = await response.blob();
console.log(blob);
const file = new File([blob], "image.jpg", { type: "image/jpeg" });
const uploadedFile = await uploadFile(file);
console.log("File uploaded successfully:", uploadedFile);
} catch (error) {
console.log("Error uploading file:", error);
}
};
return (
{image && (
<Image source={{ uri: image }} style={{ width: 200, height: 200 }} />
)}
);
}