如何使用react native expo上传图片到firebase存储器

zysjyyx4  于 2023-02-13  发布在  React
关注(0)|答案(1)|浏览(152)

我尝试使用我的expo应用程序将图像上传到firebase存储器。我浏览了他们的文档,并尝试使用文档实现。但无论何时上传,我都没有收到任何错误,但出现在firebase上的图像只是一个普通的白色框
图像上传至Firebase

查看预览时出错

这是我的全部代码

import React, { useState } from 'react';
import { Image, View, Text, Button, ActivityIndicator } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { app } from './firebaseConfig';
import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
import 'firebase/storage'; 

const App = () => {
  const [image, setImage] = useState(null);
  const [uploading, setUploading] = useState(false);

  

  const pickImage = async () => {
    try {
      let result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: true,
        aspect: [4, 3],
        quality: 1,
      });
      if (!result.canceled) {
        console.log(result.assets[0].uri)
        setImage(result.assets[0].uri);
      }
    } catch (E) {
      console.log(E);
    }
  };

const storage = getStorage(app);
  // Create the file metadata
/** @type {any} */
const metadata = {
  contentType: 'image/jpeg'
};

// Upload file and metadata to the object 'images/mountains.jpg'
const storageRef = ref(storage, 'images/' + Date.now());
const uploadTask = uploadBytesResumable(storageRef, image, metadata);

console.log(storageRef)
// 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);
    });
  }
);

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button title="Pick an image from camera roll" onPress={pickImage} />
      {image && (
        <>
          <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />
        </>
      )}
      {uploading && <ActivityIndicator />}
    </View>
  );
};

export default App;
mf98qq94

mf98qq941#

expo-image-picker返回的URL路径result.assets[0].uri是对图像数据的引用,但不包含实际的图像数据。
由于firebase希望上传二进制数据,因此应用需要首先获取图像二进制数据。

const getBlobFroUri = async (uri) => {
  const 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);
  });

  return blob;
};

const imageBlob = await getBlobFroUri(image)

const uploadTask = uploadBytesResumable(storageRef, imageblob, metadata);

我写过一篇关于这个主题的深入文章-https://dev.to/emmbyiringiro/upload-image-with-expo-and-firebase-cloud-storage-3481

相关问题