【问题标题】:How upload file(photo) to firebase storage in version-9 by react native expo如何通过 react native expo 将文件(照片)上传到版本 9 中的 Firebase 存储
【发布时间】:2021-11-30 13:00:14
【问题描述】:

我正在尝试将照片上传到 Firebase 存储。 旧方法在 firebase 新版本中不起作用 我需要帮助如何为 firebase version9 执行上传功能。

这是我的 firebase.js

// Import the functions you need from the SDKs you need
import {initializeApp } from "firebase/app";
import {getAuth} from 'firebase/auth';
import {getFirestore} from 'firebase/firestore';
import { getStorage, ref, uploadBytes } from 'firebase/storage';
import firebase from 'firebase/compat/app';
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "AIzaSyBLc-5dJjxHSxt1-GLCh0eNKHKN8jnhPLk",
  authDomain: "image-22e99.firebaseapp.com",
  projectId: "image-22e99",
  storageBucket: "image-22e99.appspot.com",
  messagingSenderId: "71958952042",
  appId: "1:71958952042:web:22638e27a52d86d5a73213"
};



// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth();
const db = getFirestore();
const storage = getStorage();
const ref = ref();
const uploadBytes = uploadBytes();

export {db , auth, storage ,ref, uploadBytes};
export default firebase;


这是我的 app.js 我已经尝试过旧方法 它显示 storage.ref 在新的 firebase 版本中不起作用

import * as ImagePicker from 'expo-image-picker';
import React, { useEffect, useState } from 'react';
import {
  ActivityIndicator,
  Button,
  Image,
  SafeAreaView,
  StyleSheet,
} from 'react-native';

import { storage ,ref,uploadBytes} from './firebase';


export default function App() {
  const [imageUri, setImageUri] = useState(null);
  const [uploading, setUploading] = useState(false);

  useEffect(() => {
    getPermission();
  }, []);

  const getPermission = async () => {
    if (Platform.OS !== 'web') {
      const { status } =
        await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (status !== 'granted') {
        alert('Sorry, we need camera roll permissions to make this work!');
      }
    }
  };

  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    console.log(result);

    if (!result.cancelled) {
      setImageUri(result.uri);
    }
  };


 const upload = 



  return (
    <SafeAreaView style={styles.container}>
      <Image source={{ uri: imageUri }} style={{ width: 300, height: 300 }} />
      <Button title='Choose picture' onPress={pickImage} />

      {uploading ? (
        <ActivityIndicator />
      ) : (
        <Button title='Upload' onPress={upload} />
      )}

      
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

我需要上传功能方面的帮助 有人能帮助我吗 谢谢你

【问题讨论】:

标签: javascript firebase react-native expo


【解决方案1】:

此 TypeScript 函数将文件数组上传到存储桶并返回包含对象 {name: string, downloadURL: string, fullPath: string} 的数组

async function uploadFiles(path: string, files: File[], id: string) {
    if (!files.length || !path || !id) throw Error('There are no files, path or id')
    const promises = []
    const data = []
    for (const item of files) {
        const storageRef = ref(storage, `${path}/${id}_${item.name}`)
        promises.push(uploadBytes(storageRef, item))
    }
    const uploadResults = await Promise.all(promises)
    const downloadURLs = []

    for (const item of uploadResults) {
        data.push({ fullPath: item.metadata.fullPath, downloadURL: '', name: '' })
        downloadURLs.push(getDownloadURL(item.ref))
    }

    const downloadURLsResult = await Promise.all(downloadURLs)

    for (var i = 0; i < downloadURLsResult.length; i++) {
        data[i].downloadURL = downloadURLsResult[i]
        data[i].name = files[i].name
    }

    return data
}

【讨论】:

    猜你喜欢
    • 2021-11-30
    • 1970-01-01
    • 2019-10-11
    • 1970-01-01
    • 2019-04-18
    • 2021-10-09
    • 1970-01-01
    • 2020-06-30
    • 2021-12-02
    相关资源
    最近更新 更多