【问题标题】:getDownloadURL does not work correctly - Firebase Storage (Web)getDownloadURL 无法正常工作 - Firebase 存储(网络)
【发布时间】:2016-12-05 15:00:28
【问题描述】:

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

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

那么如何获取下载地址呢?

【问题讨论】:

    标签: javascript firebase firebase-storage


    【解决方案1】:

    上传文件是一个异步操作,可能需要一些时间才能完成。由于您的代码未处理该问题,因此您在文件尚未完成上传时检索下载 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;
    });
    

    可以看到这个例子在上传完成后获取了下载地址。

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

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

    【讨论】:

    • 感谢您的代码。我实际上知道 downloadURL 函数没有给我我想要的 URL,因为上传文件需要时间,但我只是不知道代码应该是什么样子。无论如何,非常感谢。
    猜你喜欢
    • 2021-10-06
    • 1970-01-01
    • 2019-02-13
    • 2018-11-12
    • 2014-10-04
    • 2013-05-13
    相关资源
    最近更新 更多