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

getDownloadURL does not work correctly - Firebase Storage (Web)

本文关键字:-Firebase 存储 Web 工作 常工作 getDownloadURL      更新时间:2023-09-26

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

获取。。。{不是下载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
      });

那么我该如何获得下载URL呢?

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

从上传文件到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;
});