首页 > 解决方案 > 如何从 Firebase 存储下载 pdf

问题描述

当我尝试从 Firebase Storage 下载 pdf 时出现此错误:Access to XMLHttpRequest at "document.pdf" from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.现在我已将存储桶的 cors.js 配置为没有任何限制。但是当我点击按钮下载时,没有任何东西打开并且没有下载任何东西。

我的网页中有一个按钮 onClick 它调用downloadInvoice()客户端的函数:

function downloadInvoice(){
    var invoiceRef = firebase.storage().ref('pedidos/' + id +'.pdf');

    // Get the download URL
    invoiceRef.getDownloadURL().then(function(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();
    }).catch(function(error) {

        // A full list of error codes is available at
        // https://firebase.google.com/docs/storage/web/handle-errors
        switch (error.code) {
            case 'storage/object-not-found':
            // File doesn't exist
            break;

            case 'storage/unauthorized':
            // User doesn't have permission to access the object
            break;

            case 'storage/canceled':
            // User canceled the upload
            break;

            case 'storage/unknown':
            // Unknown error occurred, inspect the server response
            break;
        }
    });
}

URL 是正确的,因为当我遇到错误时,我可以从浏览器的控制台打开文档。

标签: javascriptfirebasefirebase-storagewebclient

解决方案


推荐阅读