首页 > 解决方案 > 在反应中使用 Firebase 存储

问题描述

我正在尝试将使用 dataToUrl 创建的 pdf 上传到 firebase,但我不断获得未经授权的 403 存储。

我做了 npm i @firebase/storage --save 并在我的 package.json 中说:

"@firebase/storage": "^0.3.32",

我有一个存储我的 firebase 凭据的文件 firebase.js:

import * as firebase from 'firebase';
import 'firebase/auth';
import 'firebase/firestore';
import '@firebase/storage';

const firebaseConfig = {
    ...my details here
};

firebase.initializeApp(firebaseConfig);

export default firebase;

如果我尝试像文档中所说的那样初始化存储桶,那么它不会加载:

const bucket = "my-app-xxxxx.appspot.com/";

firebase.initializeApp(
    {
        credential: firebaseConfig, 
        storageBucket: bucket
    }
 );

我将 DOM 转换为 jpeg,然后将 jpeg 转换为 pdf 然后存储 pdf 的代码到目前为止是这样的:

import firebase from '../../Utils/firebase';

import uuid from 'react-uuid'
import 'firebase/auth';
import 'firebase/firestore';
import '@firebase/storage';


domtoimage.toJpeg(node, {width: reportInViewerRef.current.offsetWidth * 2, height: reportInViewerRef.current.scrollHeight * 2})
            .then(function (dataUrl) {
                const pdf = new jsPDF('p', 'px', [reportHeight - 20, reportWidth]);

                pdf.addImage(dataUrl, 'JPEG', 0, -12, reportWidth, reportHeight);
                pdf.save("download.pdf"); 

                var storageRef = firebase.storage().ref();
                var fileLocation = getUniqueFilename() + '.jpg'
                var reportPdfRef = storageRef.child(fileLocation);
                reportPdfRef.putString(dataUrl, 'data_url').then(function(snapshot) {
                    console.log('Uploaded a data_url string!', reportPdfRef);

                  });
                // download(dataUrl, 'my-node.jpg')
            })
        .catch(function (error) {
            console.error('oops, something went wrong!', error);
        });

我的存储规则是:

rules_version = '2';
service firebase.storage {
  match /b/my-app-xxxxx.appspot.com/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}

任何见解表示赞赏!

标签: reactjsfirebasefirebase-storage

解决方案


推荐阅读