React Native + Firebase存储:base64和blob无法正常工作

时间:2017-04-20 09:02:13

标签: firebase react-native firebase-storage

我正在尝试将我的图像文件编码为base64或blob,但它们都不起作用。我也使用它:https://github.com/react-community/react-native-image-picker来管理图像选择器。

尝试1:使用Image picker的.data方法,该方法应返回base64字符串

const blah = uuid.v4();
firebase
  .storage()
  .ref('images')
  .child(`${blah}.jpg`)
  .putString(file.data, 'base64', { contentType: 'image/jpeg' })

但这会引发:Firebase Storage: String does not match format 'base64': Invalid character found

使用https://github.com/wkh237/react-native-fetch-blob

尝试2:Blob
      const uri = file.uri;
      const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri
      data = RNFetchBlob.fs.readFile(uploadUri, 'base64')
      blob = RNFetchBlob.polyfill.Blob.build(data, { type: 'application/octet-stream;BASE64' })
      const uniqueId = uuid.v4();
      const firebaseRef = firebase.storage().ref('images').child(`${uniqueId}.jpg`)
      return Observable.fromPromise(firebaseRef.put(blob, { contentType: 'application/octet-stream;BASE64' }));
    })

但是,它正在返回:Firebase Storage: Invalid argument inat index 0: Expected Blob or File.

使用https://github.com/wkh237/react-native-fetch-blob

尝试3:base64
      const uri = file.uri;
      const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri
      data = RNFetchBlob.fs.readFile(uploadUri, 'base64')
      const uniqueId = uuid.v4();
      const firebaseRef = firebase.storage().ref('images').child(`${uniqueId}.jpg`)
      const metadata= {
        contentType: 'image/jpeg',
      };
      firebaseRef.putString(data, 'base64', metadata);

但这再次抛出:Firebase Storage: String does not match format 'base64': Invalid character found

有谁知道我做错了什么?

2 个答案:

答案 0 :(得分:2)

回想我最近使用5.5.6版的那一天,我更新到了6.2.0版并遇到了同样的问题。

const uri = Platform.OS === 'ios' ? response.uri.replace('file://', '') : response.uri
const imageRef = storage().ref('images/').child("blah")
await imageRef.put(uri)
const imageUrl = await imageRef.getDownloadURL()

我刚刚将.put更改为.putFile,一切又恢复正常了

答案 1 :(得分:0)

关于(尝试1)您必须使用' data_url':

.putString(file.data, 'data_url', { contentType: 'image/jpeg' })