我正在将图像上传到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;
      });
}任何帮助都将不胜感激,因为我不知道如何处理这种情况的确切路径
发布于 2019-07-02 19:42:04
你可以使用下面的代码,它会给你完成图片上传的百分比。
例如;
...
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);
});
...发布于 2019-07-02 21:57:40
上传图片到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)
    });
  }https://stackoverflow.com/questions/56851412
复制相似问题