Fakultas Ilmu Komputer UI

images.tsx 1.57 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import * as ImagePicker from "expo-image-picker";
import { Alert } from "react-native";
import firebase from "firebase/app";
import "firebase/storage";

export const pickImage =
  async (): Promise<ImagePicker.ImagePickerResult | null> => {
    const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (status !== "granted") {
      Alert.alert("Unable to grant access to gallery");
      return null;
    } else {
      const pickerResult = await ImagePicker.launchImageLibraryAsync({
        allowsEditing: true,
        aspect: [1, 1],
      });

      return pickerResult;
    }
  };

export const uploadImgToFirebase = async (
  uri: string,
  path: string,
  setLoading?: React.Dispatch<React.SetStateAction<boolean>>
): Promise<string> => {
  try {
    setLoading && setLoading(true);
29
    console.log("ayam");
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

    const blob: Blob = await new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.onload = function () {
        resolve(xhr.response);
      };
      xhr.onerror = function (e) {
        console.log(e);
        reject(new TypeError("Network request failed"));
      };
      xhr.responseType = "blob";
      xhr.open("GET", uri, true);
      xhr.send(null);
    });

    const ref = firebase.storage().ref().child(path);
    const snapshot = await ref.put(blob);

    // We're done with the blob, close and release it
    // blob.close();

    return (await snapshot.ref.getDownloadURL()) as string;
  } catch (e) {
    console.log(e);
    Alert.alert("Upload failed");
  } finally {
    setLoading && setLoading(false);
  }
};