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

时间:2016-07-31 11:24:53

标签: javascript firebase firebase-storage

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

  

GET ... {不是下载网址的网址} ... 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
      });

那么如何获得downloadURL?

1 个答案:

答案 0 :(得分:2)

上传文件是一种异步操作,可能需要一些时间才能完成。由于您的代码未对此进行处理,因此您尚未在文件尚未完成上传时检索下载网址。

来自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;
});