【问题标题】:Firebase Download Image using Download URL (Without Calling Storage)Firebase 使用下载 URL 下载图像(不调用存储)
【发布时间】:2018-01-09 05:51:45
【问题描述】:

Firebase's documentation 涵盖下载图像如果您调用存储和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
});

但是,我已经有一个 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 存储)?

【问题讨论】:

  • 如果你看一下浏览器的开发者工具,它会显示一些错误吗?
  • @RaxWeber 在浏览器的开发工具中没有显示错误

标签: javascript firebase download firebase-storage


【解决方案1】:

这最终对我有用:

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 创建一个 a href,然后在收到 xhr 响应时以编程方式单击 a href

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

【讨论】:

  • 当您在移动设备上加载网站时,这项工作是否有效。我真的很高兴这终于对我有用,我一直在寻找解决方案。现在我仍然无法为移动设备触发相同的操作
  • 令人敬畏的作品就像魅力!
猜你喜欢
  • 2018-05-02
  • 2018-08-09
  • 2020-11-06
  • 2016-12-28
  • 2018-02-04
  • 2021-10-23
  • 1970-01-01
  • 2020-02-29
  • 1970-01-01
相关资源
最近更新 更多