【问题标题】:Download image from firebase storage web - vuejs从 Firebase 存储网络下载图像 - vuejs
【发布时间】:2022-01-02 15:29:01
【问题描述】:

我正在尝试在将下载图像的图像上实现下载按钮。由于图像托管在 Firebase 存储上,因此我使用他们的代码变体来检索我在官方文档中找到的文件:https://firebase.google.com/docs/storage/web/download-files#download_data_via_url

我对其进行了一些更改,因为在示例中,代码正在从存储桶上的路径中检索文件 url,而在我的情况下,我已经知道该 url:

download(url) {
  const xhr = new XMLHttpRequest();
  xhr.responseType = "blob";
  xhr.onload = () => {
    xhr.response;
  };
  xhr.open("GET", url);
  xhr.send();
},

现在的问题是请求获取的图像但没有触发下载(到用户的机器):

我知道我真的很接近,我如何触发图片下载?此外,由于图像已经显示在网站上,我真的需要从 firebase 调用它吗?

解决方案:

感谢 Renaud 的帮助,我能够修复我的代码:

    download(url) {
      const xhr = new XMLHttpRequest();
      xhr.responseType = "blob";
      xhr.onload = () => {
        var urlCreator = window.URL || window.webkitURL;
        var imageUrl = urlCreator.createObjectURL(xhr.response);
        const link = document.createElement("a");
        link.href = imageUrl;
        link.setAttribute("download", "test");
        link.setAttribute("target", "new");
        document.body.appendChild(link);
        link.click();
      };
      xhr.open("GET", url);
      xhr.send();
    },

请随时发布对此解决方案的优化。

【问题讨论】:

    标签: firebase vue.js download google-cloud-storage firebase-storage


    【解决方案1】:

    一种可能的方法是在页面中创建一个隐藏链接并模拟点击此链接,如下所示:

    // Get the URL. You have it since you call download(url)
    // In case you don't have the URL, use const url = await getDownloadURL(fileRef);
    const url = ...
    
    
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', fileName);
    link.setAttribute('target', 'new');
    document.body.appendChild(link);
    link.click();
    

    【讨论】:

    • 嗨雷诺,谢谢你的回答。不幸的是,这只是在新标签中打开图像。
    • 这是使用您的代码创建的 a 元素:<a href="https://..." download="test.png" target="new"></a>
    • 哦,我明白了...我使用此代码下载存储在 Cloud Storage 中的 PDF 和 Word 文档,在这种情况下会打开下载打开对话框。对于图像,行为是不同的,这是有道理的……我会在几分钟内删除这个答案。我会尝试另一种方式,并可能会发布一个新的答案。
    • 嗨 Renaud 我能够调整您的代码并找到解决方案。我会用它更新我的答案并接受你的答案。
    猜你喜欢
    • 2016-12-28
    • 1970-01-01
    • 2017-01-16
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    相关资源
    最近更新 更多