使用下载URL的FireBase下载映像(不调用存储) [英] Firebase Download Image using Download URL (Without Calling Storage)

查看:0
本文介绍了使用下载URL的FireBase下载映像(不调用存储)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Firebase's documentation如果您调用存储和getDownloadURL

Firebase's documentation介绍如何下载镜像,我可以很好地使用它(直接从文档中获取):

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存储)吗?

推荐答案

这最终为我工作:

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

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

这篇关于使用下载URL的FireBase下载映像(不调用存储)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆