如何获取上传图像的uri

时间:2018-11-19 15:23:39

标签: ios firebase react-native react-native-ios

我正在使用Firebase Storage创建图像URL并将其发送到Firebase Storage Bucket。当我具有上传权限和Firebase存储配置集时,我的工作情况良好。但是,如何从图像中获取实际的URI并进行查看?我已经在JS中看到了一些可能的答案。但不是本机反应。这是我的代码:

submitFormHandler = () => {
    console.log("FormHandler: " + this.state.message)
    let isFormValid = true;
    let dataToSubmit = {};
    const formCopy = this.state.form;

    var user = firebase.auth().currentUser;

    for (let key in formCopy) {
      isFormValid = isFormValid && formCopy[key].valid;
      dataToSubmit[key] = this.state.form[key].value;
    }

    if (isFormValid, user) {
      this.setState({
        loading: true
      });

      getTokens((value) => {
        const dateNow = new Date();
        const expiration = dateNow.getTime();
        const form = {
          ...dataToSubmit,
          uid: value[3][1]
        }

        if (expiration > value[2][1]) {
          this.props.autoSignIn(value[1][1]).then(() => {
            setTokens(this.props.User.userData, () => {

              this.props.addArticle(form, this.props.User.userData.token).then(() => {
                this.setState({ modalSuccess: true })
              })
            })
          })
        } else {
          this.props.addArticle(form, value[0][1]).then(() => {
            this.setState({ modalSuccess: true })
          })
        }
      })

    } else {
      let errorsArray = [];

      for (let key in formCopy) {
        if (!formCopy[key].valid) {
          errorsArray.push(formCopy[key].errorMsg)
        }
      }

      this.setState({
        loading: false,
        upload: true,
        hasErrors: true,
        modalVisible: true,
        errorsArray
      })
    }
  }

  showErrorsArray = (errors) => (
    errors ?
      errors.map((item, i) => (
        <Text key={i} style={styles.errorItem}> - {item}</Text>
      ))
      : null
  )

  clearErrors = () => {
    this.setState({
      hasErrors: false,
      modalVisible: false,
      errorsArray: []
    })
  }

  resetDenEventScreen = () => {
    const formCopy = this.state.form;

    for (let key in formCopy) {
      formCopy[key].valid = false;
      formCopy[key].value = "";
    }

    this.setState({
      modalSuccess: false,
      hasErrors: false,
      errorsArray: [],
      loading: false
    })

    this.props.resetArticle();

  }

然后将图像URL传递到Firebase,并将其设置为“ imageSource”的键和“ .jpg”的值。使用硬编码,这可以正常工作,但是仅当我为从用户(或Firebase Storage中的文件夹)添加的图像设置了URI时。我知道Firebase Realtime Database如何将自己的ID号分配给某项,如下所示:

pickImage = () => {
    console.log('onPickImage');
    this.setState({ imageLoading: true });
    ImagePicker.showImagePicker(null, (response) => {
      console.log('Response = ', response);
      if (response.didCancel) {
        console.log('User cancelled image picker');
        this.setState({ imageLoading: false });
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
        this.setState({ imageLoading: false });
      } else {
        const source = {
          uri: response.uri,
          type: response.type,
        };
        this.setState({ localImageSource: source.uri });
      }
    });
  }

uploadImage(imageSource) {
    console.log("starting upload image...");
    return new Promise((resolve, reject) => {
      const uploadUri = Platform.OS === 'ios' ? imageSource.uri.replace('file://', '') : imageSource.uri;
      let uploadBlob = null;

      const imageRef = firebase.storage().ref('images/').child(imageSource.uri)
      fs.readFile(uploadUri, 'base64')
        .then((data) => {
          console.log("building blob...");
          return Blob.build(data, { type: '${mime};BASE64' });
        })
        .then((blob) => {
          uploadBlob = blob;
          console.log("uploading blob...");
          return imageRef.put(uploadUri, { contentType: imageSource.type });
        })
        .then(() => {
          uploadBlob.close();
          console.log("getting blob downloadUrl...");
          return imageRef.getDownloadURL();
        })
        .then((url) => {
          console.log('Image URL: ', url);
          console.log("resolving...")
          resolve(url);
        })
        .catch((error) => {
          console.log("rejecting promise..." + error);
          reject(error)
        });
      // this.handlePickedImage(pickerResult);
    });

  }

其中item.key是由Firebase生成的,因此不必进行硬编码。是否可以在Firebase Storage中为图像和“商品”实现此功能?而且我真的需要分配新的密钥在Firebase存储中添加条目吗,因为移动应用程序仅将URL上传到Firebase,现在我需要从图像中获取URI。

handlePickedImage = pickerResult => {
    try {
      this.setState({ uploading: true });

      if (!pickerResult.cancelled) {
        uploadUrl = awaituploadImage(pickerResult.uri);
        this.setState({ image: uploadUrl });
      }
    } catch (e) {
      console.log(e);
      alert('Upload failed, sorry : (');
    } finally {
      this.setState({ uploading: false });
    }
  };

  getImageLocal() {
    console.log('Attempting to get localImageSource: ' + this.state.localImageSource);
    if (this.state.localImageSource == null) {
      console.log("localImageSource was not available, aborting...");
      return;
    }
    return (
      <Image
        style={styles.imageStyle}
        source={{ uri: this.state.localImageSource }} />
    );
  }

  getImage() {
    console.log('Attempting to get imageSource: ' + this.state.imageSource);
    if (this.state.imageSource == null) {
      console.log("imageSource was not available, aborting...");
      return;
    }
    return (
      <Image
        style={styles.imageStyle}
        source={{ uri: this.state.imageSource }} />
    );
  }

我知道我需要放置“ firebase.storage()。ref()。getDowloadUrl()”之类的内容,或者更简单地添加“ form.image.value.getDownloadUrl()”,并抱歉询问“ where” ?谢谢,我是新手,正在寻找许多文档,但是我对要放谁或要工作的逻辑不是很了解...

0 个答案:

没有答案