0

我正在尝试使用 Expo 将我的手机上的图片上传到 Firebase。我从图片中得到一个 uri,但不知道如何转换它,我可以将它上传到 Firebase?

  _pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      allowsEditing: true,
      aspect: [4, 3],
    });

    if (!result.cancelled) {
      console.log('device URL: w',result.uri);
      this.setState({ image: result.uri });
      this.uploadImage(result.uri).then(resp =>{
        alert('success')
      }).catch(err=>{
        console.log(err)
      })
    }
  };

当我记录 result.uri 我得到:

file:///var/mobile/Containers/Data/Application/1E5612D6-ECDB-44F4-9839-3717146FBD3E/Library/Caches/ExponentExperienceData/%2540anonymous%252FexpoApp-87f4a5f5-b117-462a-b147-cab242b0a916/ImagePicker/45FA4A7- C174-4BC9-B35A-A640049C2CCB.jpg

如何将其转换为适用于 firebase 的格式?

4

2 回答 2

0

您可以将图像转换为 base64,有几个库可以做到这一点。

于 2018-12-13T21:39:29.740 回答
0

您需要将图像转换为 base64,这是使用 rn-fetch-blob https://github.com/joltup/rn-fetch-blob的示例

 export const picture = (uri, mime = 'application/octet-stream') => {
  //const mime = 'image/jpg';
  const { currentUser } = firebase.auth();  
  const Blob = RNFetchBlob.polyfill.Blob;
  const fs = RNFetchBlob.fs;
  window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
  window.Blob = Blob;

  return ((resolve, reject) => {
      const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri;
      let uploadBlob = null;
      const imageRef = firebase.storage().ref('your_ref').child('child_ref');
      fs.readFile(uploadUri, 'base64')
      .then((data) => {
        return Blob.build(data, { type: `${mime};BASE64` });
      })
      .then((blob) => {
        uploadBlob = blob;
        imageRef.put(blob._ref, blob, { contentType: mime });
      })
      .then(() => {
        //take the downloadUrl in case you want to downlaod
        imageRef.getDownloadURL().then(url => {
         // do something
        });
      });
  });
};
于 2018-12-14T01:05:05.753 回答