在Firebase存储上载完成后,如何获取下载URL

时间:2018-07-22 09:13:38

标签: javascript firebase firebase-storage

图像上传完成后,我想获取下载URL,然后将downloadURL设置为我的newAds.picLink(object.property),但是在此代码中,因为正在进行上传

public_html/uk
调用

会引发错误,因为downloadURL当前不可用且正在进行中。我已通过使用setTimeOut来解决此问题,该设置为8秒钟,它允许图像首先完全上传,然后接收到downloadURL,但这是不正确的。

一旦图像完全上传,如何创建一个正确的回调来设置newAds.picLink = downloadURL?

newAds.update({ picLink: downloadURL });

2 个答案:

答案 0 :(得分:2)

来自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。

答案 1 :(得分:1)

put()返回一个UploadTask,您可以像正常的承诺那样使用它,因为它声明了一个then()方法:

const task = ref.child(name).put(file, {contentType: file.type});
task.then(snapshot => {
    ref.getDownloadURL().then(...);
});
相关问题