import { View, Text, Image } from "react-native"
import * as ImagePicker from "expo-image-picker"
import React, { Dispatch, SetStateAction, useState } from "react"
import { storage } from "../firebase"
import { Button } from "react-native-paper"
type UrploadImageType = {
setUri: Dispatch<SetStateAction<string>>
}
const UploadImage = ({ setUri }: UrploadImageType) => {
const [image, setImage] = useState<string | null>()
const pickImage = async () => {
// No permissions request is necessary for launching the image library
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
})
if (!result.canceled) {
setImage(result.assets[0].uri)
setUri(result.assets[0].uri)
}
}
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
{image && (
<Image source={{ uri: image }} style={{ width: 200, height: 200 }} />
)}
<Button onPress={pickImage}>Pick an image from camera roll</Button>
</View>
)
}
export default UploadImage
const getBlobForUri = async (uri: string) => {
if (uri) {
const blob: Blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.onload = function () {
resolve(xhr.response)
}
xhr.onerror = function (e) {
reject(new TypeError("Network request failed"))
}
xhr.responseType = "blob"
xhr.open("GET", uri, true)
xhr.send(null)
})
uploadImage(blob)
}
}
import { ref, uploadBytesResumable, getDownloadURL } from "firebase/storage"
import { storage } from "../firebase"
const uploadImage = async (blob: Blob) => {
const metadata = {
contentType: "image/png",
}
// Upload file and metadata to the object 'images/mountains.jpg'
const storageRef = ref(storage, "images/" + blob)
const uploadTask = uploadBytesResumable(storageRef, blob, metadata)
// Listen for state changes, errors, and completion of the upload.
uploadTask.on(
"state_changed",
(snapshot) => {
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
console.log("Upload is " + progress + "% done")
switch (snapshot.state) {
case "paused":
console.log("Upload is paused")
break
case "running":
console.log("Upload is running")
break
}
},
(error) => {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case "storage/unauthorized":
// User doesn't have permission to access the object
break
case "storage/canceled":
// User canceled the upload
break
// ...
case "storage/unknown":
// Unknown error occurred, inspect error.serverResponse
break
}
},
() => {
// Upload completed successfully, now we can get the download URL
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
console.log("File available at", downloadURL)
})
}
)
}