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

Rba*_*bar 2 javascript download firebase firebase-storage

Firebase 的文档涵盖了在调用 storage 和 时getDownloadURL下载图像,并且我可以正常工作(直接来自文档):

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
});
Run Code Online (Sandbox Code Playgroud)

但是,我已经有了一个 URL,并且想在不调用 firebase storage 的情况下下载图像。这是我的尝试:

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();
Run Code Online (Sandbox Code Playgroud)

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

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

有谁知道如何使用您已有的下载 URL 下载图像(不像文档中那样调用 Firebase Storage)?

Rba*_*bar 6

这最终对我有用:

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();
Run Code Online (Sandbox Code Playgroud)

这实质上是创建一个a href指向我拥有的 URL,然后在收到响应a href时以编程方式单击该 URL xhr

我不清楚为什么第一种方法不起作用,但希望这可以帮助面临同样问题的其他人。