React Native多个图像

时间:2017-10-25 11:43:57

标签: javascript firebase react-native firebase-storage

您能告诉我有关上传多张图片的源代码吗?我试图将多个图像上传到我的firebase。所以我使用 react-native-image-crop picker 来选择图像,然后做出native-fetch-blob 以在上传到firebase之前转换图片。在选择图像之后,我循环数组然后转换为在循环内获取blob。但有时它可以工作,但有时图像网址是空的。我希望我能在这里找到答案

1 个答案:

答案 0 :(得分:3)

试试这个:

const uploadImages = (photos) => {
  const uploadImagePromises = _.map(photos, (p, index) => uploadImage({ uri: p, imageName: "image_" + index }))
  const urls = await Promise.all(uploadImagePromises)
  console.log(urls);
}


const uploadImage = ({ uri, imageName }) => {
  const Blob = RNFetchBlob.polyfill.Blob
  const fs = RNFetchBlob.fs
  window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
  window.Blob = Blob
  const mime = 'image/jpg'
  return new Promise((resolve, reject) => {
    const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri
    let uploadBlob = null
    const imageRef = firebase.storage().ref('/images/').child(imageName)
    fs.readFile(uploadUri, 'base64')
      .then((data) => {
        return Blob.build(data, { type: `${mime};BASE64` })
      })
      .then((blob) => {
        uploadBlob = blob
        return imageRef.put(blob, { contentType: mime })
      })
      .then(() => {
        uploadBlob.close()
        resolve(imageRef.getDownloadURL())
      })
      .catch(error => {
        console.log("error", error);
        reject()
      })
  })
}