如何使用React Native将图像上传到Firebase

时间:2019-09-05 00:38:46

标签: react-native

我需要将图像上传到Firebase的方法

我试图使用react-native-fetch-blob库

但是我认为安装库有问题

2 个答案:

答案 0 :(得分:0)

async function uploadImageAsync(itemImage, passedParameter, ItemName, ItemDesc, ItemPrice, ItemWeight) {



     const response = await fetch(itemImage);
      const blob = await response.blob();
       console.log("uri of the elements ius", blob)

      var storageRef = firebase.storage().ref();
      var file = blob

     var metadata = {
        contentType: 'image/jpeg',
      };
      const timeStamp = Date.now();
      var uploadTask = storageRef.child('CategoryDescription' + "/" + `${passedParameter}` + "/" + `${ItemName}`).put(file, metadata);

//对于图像拾取

pickImage = async () => {
 const { CAMERA, CAMERA_ROLL } = Permissions;
 const permissions = {
  [CAMERA]: await Permissions.askAsync(CAMERA),
  [CAMERA_ROLL]: await Permissions.askAsync(CAMERA_ROLL),
 };

 if (permissions[CAMERA].status === 'granted' && permissions[CAMERA_ROLL].status === 'granted') {
  let result = await ImagePicker.launchImageLibraryAsync({
 allowsEditing: false,
 aspect:[4,3],
 quality: 0.5,
  });
  // console.log(result);

  if (!result.cancelled) {
 this.setState({ itemImage: result.uri });
  }
 }

答案 1 :(得分:0)

无需使用react-native-fetch-blob。这是我在项目中执行的操作。

  1. 同时安装react-native-firebasereact-native-image-picker。请遵循其文档指南中的安装步骤。

  2. 然后实现2个小功能来进行图像拾取并将其上传到Firebase。这是示例代码。

// 1. Import required library
import firebase from 'react-native-firebase';
import ImagePicker from 'react-native-image-picker';

// 2. Create a function to pick the image
const pickImage = () => {
  return new Promise((resolve, reject) => {
    ImagePicker.showImagePicker(pickerOptions, response => {
      if (response.didCancel) return;

      if (response.error) {
        const message = `An error was occurred: ${response.error}`;
        reject(new Error(message));
        return;
      }

      const { path: uri } = response;
      resolve(uri);
    });
  });
};

// 3. Create a function to upload to firebase
const uploadImage = async (fileName, uri) {
  return new Promise(
    (resolve, reject) => {
      firebase
        .storage()
        .ref(`uploads/${filename}`)
        .putFile(uri)
        .then(resolve)
        .catch(reject);
    }
  );
}
  1. 然后只需根据需要触发这两个功能,这是可以选择并立即上传的示例。
const pickImageAndUpload = async () => {
  const uri = await pickImage();
  const fileName = 'someImage.jpg';
  const { state, downloadURL } = await uploadImage(fileName, uri);
}