我正在将图像上传到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;
});
}
任何帮助将不胜感激,因为我没有找到处理这种情况的确切路径
答案 0 :(得分:0)
您可以使用以下代码,它将为您提供完成图片上传的百分比。
例如;
...
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);
});
...
答案 1 :(得分:0)
在firbase上上传图像并更新其他表中的URL,如下所示:
//将用户个人资料上传到Firestore并生成下载网址
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)
});
}