【问题标题】:Firesbase Storage - force download of an imageFirebase 存储 - 强制下载图像
【发布时间】:2018-11-26 02:01:49
【问题描述】:

我想强制下载存储在 Firebase 存储中的图像,但 HTML 锚点中的 download 属性不支持跨域,我无法将内容类型更改为 application/octet-stream,因为它已被使用生成缩略图。

怎么做?

【问题讨论】:

    标签: firebase google-cloud-storage google-cloud-functions firebase-storage


    【解决方案1】:

    在这种情况下,您不能在 html 锚点中使用简单的“下载”。

    您可以做的是通过 javascript 发送下载请求。

    有官方样本可供下载。

    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
    });
    

    【讨论】:

    • 我做到了,但我收到此错误:“从源 'localhost:8080' 访问 XMLHttpRequest 在 storage_url 已被 CORS 策略阻止:没有'访问控制-Allow-Origin' 标头出现在请求的资源上。"
    • 哦,我明白了。这应该会有所帮助,关于how to use CORS
    • 谢谢。我配置了 CORS,上面的错误消失了,但是调用 xhr.send() 时什么也没发生。我没有设置 image.src 因为这个想法是强制下载。
    • 这很好,如果您发布有问题的代码,其他用户将很容易帮助和识别问题。
    • 我认为您的代码是正确的,您无法获取图像的原因是因为没有img 可显示或form 可下载。这应该对creating a download form 有所帮助或将其设置为imgvar img = document.getElementById('myimg'); img.src = url;
    猜你喜欢
    • 2016-12-28
    • 2017-01-16
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    • 2019-03-11
    相关资源
    最近更新 更多