【问题标题】:How to wait for the specific time while uploading image to the firebase如何在将图像上传到 Firebase 时等待特定时间
【发布时间】:2019-07-02 11:26:15
【问题描述】:

我正在将图像上传到 firebase 并从中获取 imageUrl,但问题是我无法等待特定调用结束并在获取 imageURL 之前执行该过程

我也尝试过 Promise 和 Async 函数等待,但问题没有解决

下面是我的 js 文件,其中首先调用 addItem ,然后我将图像上传到 firebase 并且该 URL 想要推送到 firebase 数据库

import { db,fireBaseObj } from '../firebase/db';
import RNFetchBlob from 'react-native-fetch-blob';

export const addItem  =  (userId,title,description,isdone,PriorityIndex,PriorityValue,image_path)   => {
     uploadImage(image_path) // Here is my upload image function
     db.ref('/items/'+userId+'/').push({
        title: title,
        description: description,
        isdone: isdone,
        PriorityIndex:PriorityIndex,
        PriorityValue:PriorityValue,
       }).then(res =>{
        return true;
      }).catch(error =>{
     return false;
  })

} 



export const uploadImage =  (image_path) => {
    const Blob = RNFetchBlob.polyfill.Blob;
    const firestore = RNFetchBlob.fs;
    window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
    window.Blob = Blob;


    const imageName = image_path.path.substring(image_path.path.lastIndexOf("/")+1);
    let uploadBlob = null;
    const imageRef = fireBaseObj.storage().ref("ref").child(imageName);
    const mime = 'image/jpg';
    firestore.readFile(image_path.path, 'base64')
      .then((data) => Blob.build(data, { type: `${mime};BASE64` })
    )
    .then((blob) => {
        uploadBlob = blob;
        return imageRef.put(blob, { contentType: mime });
      })
      .then(() => {
        uploadBlob.close();
        return imageRef.getDownloadURL();
      })
      .then((url) => {
        const obj = {};
        obj.loading = false;
        obj.dp = url;

        this.setState(obj);
        return url;

      })
      .catch((error) => {
        console.log(error);
        return error;
      });
}

任何帮助将不胜感激,因为我没有得到如何处理这种情况的确切路径

【问题讨论】:

    标签: firebase react-native redux react-redux firebase-storage


    【解决方案1】:

    你可以使用下面的代码,它会给你图片上传完成的百分比。

    例如;

    ...
    return new Promise((resolve, reject) => {
      let formData = new FormData();
    
      let fileName = "name.jpeg";
    
      formData.append("file", {
        name: fileName,
        uri: media_uri,
        type: "image/jpeg"
      });
    
      var xhr = new XMLHttpRequest();
    
      xhr.upload.onprogress = function(e) {
        var percentComplete = Math.ceil((e.loaded / e.total) * 100);
        // Here you will get the percentage of completion
      };
    
      xhr.open('POST', API_URL);
      xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
          let resp = xhr.response;
          var response = JSON.parse(resp);
          resolve(response);
        } else {
          reject({
            status: xhr.status,
            statusText: xhr.statusText
          });
        }
      };
      xhr.onerror = function() {
        reject({
          status: xhr.status,
          statusText: xhr.statusText
        });
      };
    
      xhr.setRequestHeader("Authorization", `Bearer ${token}`); // If you have Authorization use it.
      xhr.send(formData);
    });
    ...
    

    【讨论】:

    • 谢谢,但我不需要百分比,因为db.ref('/items/'+userId+'/').push({(问题中给出的我的代码行)在上传文件时仍然会执行
    【解决方案2】:

    在 firbase 上上传图片并在其他表中更新 url,如下所示:

    //上传用​​户配置文件到firestore并生成下载url

        async uploadImageToFirebase(uploadImage) {
    
        loaderHandler.showLoader("Uploading...");
        var self = this;
        const mime = "image/jpeg";
        var fileName = Date.now();
        try {
          const imageRef = firebase
            .storage()
            .ref("ProfilePictures")
            .child(fileName);
          await imageRef.put(uploadImage, { contentType: mime }).then(response => {
            console.log("Firebase Upload Image Res.", response);
            console.log(uploadImage + "Image Uploaded <=====");
            var image = response.downloadURL;
            this.setState({
              profilePicURL: image,
            });
            self.updateProfilePicURLInUserTable(image)
          });
        } catch (err) {
          //error(err);
          loaderHandler.hideLoader();
          console.log("err==>", err);
        }
      }
    
    
    
    updateProfilePicURLInUserTable(downloadURL) {
        var self = this;
        var userId = firebaseUserId;
        firebase.database().ref(FirebaseConstants.tb_user).child(userId).update({
          "profilePictureURL": downloadURL
        }).then((data) => {
          //success callback
          loaderHandler.hideLoader();
          console.log('update Success ')
        }).catch((error) => {
          loaderHandler.hideLoader();
          console.log('error ', error)
        });
      }
    

    【讨论】:

    • 使用此代码它将更新个人资料图片,但如何等待该屏幕直到图像上传,因为我需要在此过程中显示进度条另外目前我正在调用 后更改屏幕addItem 函数在我的问题中我已经添加了下面的代码,希望你能理解我的观点await addItem(this.state.userId,this.state.titleState,this.state.descriptionState,false,this.state.PriorityIndex,this.state.PriorityValue,this.state.filePath).then(()=&gt;{ {this.props.navigation.goBack()}});
    猜你喜欢
    • 1970-01-01
    • 2021-03-17
    • 2019-06-28
    • 2019-06-02
    • 2019-03-11
    • 1970-01-01
    • 2020-09-09
    相关资源
    最近更新 更多