使用下载URL(而不调用存储)下载Firebase图像

4
Firebase的文档涵盖了下载图像的内容,只要调用存储并使用getDownloadURL方法即可。我已经按照文档中的步骤实现了这个功能。请参考Firebase的文档
storageRef.child('images/stars.jpg').getDownloadURL().then(function(url) {
  // `url` is the download URL for 'images/stars.jpg'

  // This can be downloaded directly:
  var xhr = new XMLHttpRequest();
  xhr.responseType = 'blob';
  xhr.onload = function(event) {
    var blob = xhr.response;
  };
  xhr.open('GET', url);
  xhr.send();

  // Or inserted into an <img> element:
  var img = document.getElementById('myimg');
  img.src = url;
}).catch(function(error) {
  // Handle any errors
});

但是,我已经有一个URL,想要不调用 Firebase 存储的情况下下载图片。以下是我的尝试:

var url = "https://firebasestorage.googleapis.com/v0/b/somerandombucketname..."
console.log(url);
// This can be downloaded directly:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
  var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();

但是,在浏览器的开发工具中没有显示任何错误,也没有下载任何文件。

注意:我知道URL是正确的,因为如果我直接将URL放入浏览器搜索栏中,我可以访问该文件并下载它。

有人知道如何使用已经拥有的下载URL下载图像(而不调用Firebase Storage,就像文档中所做的那样)吗?


如果您查看浏览器的开发者工具,它是否显示了一些错误? - Rax Weber
@RaxWeber 浏览器的开发工具中没有显示任何错误。 - Rbar
1个回答

8
这是我的解决方案:

最终我成功了:

var url = "https://firebasestorage.googleapis.com/v0/b/somerandombucketname..."
var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
  var a = document.createElement('a');
  a.href = window.URL.createObjectURL(xhr.response);
  a.download = "fileDownloaded.filetype"; // Name the file anything you'd like.
  a.style.display = 'none';
  document.body.appendChild(a);
  a.click();
};
xhr.open('GET', url);
xhr.send();

这实际上是创建一个指向我拥有的URL的,然后在收到xhr响应时通过编程方式单击

我不清楚为什么第一种方法不同样有效,但希望这能帮助其他遇到相同问题的人。


这个在移动端加载网站时也有效吗?我真的很高兴这最终为我工作了,我已经寻找解决方案很长时间了。现在我仍然无法在移动设备上触发相同的操作。 - Taio
1
太棒了,像魔法一样! - Mohammed Abid Nafi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接