getDownloadURL 无法正常工作 - Firebase 存储(Web)

getDownloadURL does not work correctly - Firebase Storage (Web)

以下代码似乎没有记录正在上传的文件的下载 URL,并出现以下错误。

GET ...{URL that is not the download URL}... 404()

这是我的代码。

     //Get image
     var file = a.target.files[0];

     //create a storage reference
     var storageRef = firebase.storage().ref('images/' + file.name);

     //store the image
     var task = storageRef.put(file);

     var storage = firebase.storage();
     storageRef.child('images/'+file.name).getDownloadURL().then(function(url) {
        console.log(url);          
      }).catch(function(error) {
        // Handle any errors
      });

那么如何下载URL?

上传文件是一个异步操作,可能需要一些时间才能完成。由于您的代码未处理该问题,因此您在文件尚未完成上传时检索下载 URL。

来自 documentation for uploading files to Firebase Storage 这个例子:

// File or Blob, assume the file is called rivers.jpg
var file = ...

// Upload the file to the path 'images/rivers.jpg'
// We can use the 'name' property on the File API to get our file name
var uploadTask = storageRef.child('images/' + file.name).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
  // See below for more detail
}, function(error) {
  // Handle unsuccessful uploads
}, function() {
  // Handle successful uploads on complete
  // For instance, get the download URL: https://firebasestorage.googleapis.com/...
  var downloadURL = uploadTask.snapshot.downloadURL;
});

可以看到这个例子在上传完成后得到了下载URL

如果你不在乎进度和失败,可以这么简单:

uploadTask.on('state_changed', null, null, function() {
  var downloadURL = uploadTask.snapshot.downloadURL;
});