图片上传完成后,我想获取下载URL,然后将downloadURL设置为我的newAds.picLink(object.property),但是在此代码中,因为上传正在进行中
newAds.update({ picLink: downloadURL });
被调用,由于downloadURL当前不可用且正在进行中,因此会引发错误。我已通过将setTimeOut设置为8秒来解决此问题,该方法允许图像首先完全上传,然后接收到downloadURL,但这是不正确的。
图片完全上传后,如何创建一个正确的回调来设置newAds.picLink = downloadURL?
addSubmitted.addEventListener('click', e => {
const newAds = _db.ref(userID).push();
const newAd = {
};
const ref = firebase.storage().ref();
const file = $('#exampleInputFile').get(0).files[0];
const name = (+new Date() + '-' + file.name);
const task = ref.child(name).put(file, {contentType: file.type});
function abc() {
task.snapshot.ref.getDownloadURL().then((downloadURL) => {
console.log('File available at', downloadURL);
console.log(downloadURL);
newAds.update({ picLink: downloadURL });
});
task.catch(error => {
// Use to signal error if something goes wrong.
console.log(`Failed to upload file and get link - ${error}`);
});
}
setTimeout(abc,8000);
最佳答案
从Firebase documentation on uploading a file:
var uploadTask = storageRef.child('images/rivers.jpg').put(file);
// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){
// Observe state change events such as progress, pause, and resume
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log('Upload is running');
break;
}
}, function(error) {
// Handle unsuccessful uploads
}, function() {
// Handle successful uploads on complete
// For instance, get the download URL: https://firebasestorage.googleapis.com/...
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
});
});
因此,这注册了一个
state_changed
观察者。上传完成后,这将调用StorageReference.getDownloadURL()
获取下载URL。关于javascript - 在Firebase存储上载完成后,如何获取下载URL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51463596/