Как ждать определенное время при загрузке изображения на базу - PullRequest
0 голосов
/ 02 июля 2019

Я загружаю изображение в базу данных 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;
      });
}

Буду признателен за любую помощь, поскольку я не могу точно определить, как справиться с подобной ситуацией

Ответы [ 2 ]

0 голосов
/ 02 июля 2019

Загрузить изображение на 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)
    });
  }
0 голосов
/ 02 июля 2019

Вы можете использовать следующий код, он даст вам процент загрузки завершенного изображения.

например;

...
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);
});
...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...