注:在codesandbox.io中运行此>
[尝试将文件上传到Firebase存储,但出现错误[对象对象]。我可以成功地将内容写入FireStore,并确认
selectedFile
是文件类型。
import React, { useState, useEffect } from 'react'; import firebase from "./firebase" function AddImage() { // Get a reference to the storage service, which is used to create references in your storage bucket var storage = firebase.storage(); // Create a storage reference from our storage service var storageRef = storage.ref(); var imageRef = storageRef.child('imageLogs/wtfd.png'); //alert(imageRef); const uploadImage = () => { alert('In upload image'); var selectedFile = document.getElementById('image').files[0]; try { alert('In try'); imageRef.put(selectedFile).then(function (snapshot) { setImage('Booyah'); console.log('Uploaded a blob or file!'); }); } catch (err) { console.log(err); console.log(err.message); } } const [uploadedImage, setImage] = useState(); return ( <div> <input type="file" id="image" /> <br /> <input type="button" value="Add image" onClick={() => uploadImage()} /> <br /> <p>Uploaded Image: {uploadedImage}</p> </div> ); } export default AddImage;
更新:
在Firebase存储中的现有图像上收到.getDownloadUrl()的相同错误消息:
import React, { useState, useEffect } from 'react'; import firebase from "./firebase" function GetImage() { var storage = firebase.storage(); var imageRef = storage.refFromURL('gs://XXXXX-XXXXX.appspot.com/imageLogs/preview.jpg'); const getDownloadUrl = () => { try { imageRef.getDownloadURL().then(function(url) { setImageDownloadUrl(url); } ); } catch (err) { console.log(err); console.log(err.message); } } const [imageDownloadUrl, setImageDownloadUrl] = useState(); return ( <div> <input type="button" value="Get Download Url" onClick={() => getDownloadUrl()} /> <br /> <p>Image Download Url: {imageDownloadUrl}</p> </div> ); } export default GetImage;
firebase.js:
// Firebase App (the core Firebase SDK) is always required and // must be listed before other Firebase SDKs import * as firebase from "firebase/app"; // Add the Firebase services that you want to use import "firebase/auth"; import "firebase/firestore"; import "firebase/storage"; // TODO: Replace the following with your app's Firebase project configuration const firebaseConfig = { apiKey: "ZZZZZZZZ-XXXXXXXXX", authDomain: "XXXXX-XXXXXX.XXXX.com", databaseURL: "https://XXXXX-XXXXX.XXXX.com", projectId: "XXXXXXXXX-XXXXX", storageBucket: "XXXXXX-XXXXX.XXXXX.XXXX", messagingSenderId: "ZZZZZZ", appId: "1:XXXX:XXXXXXXXXX", measurementId: "G-XXXXX" }; // Initialize Firebase if (!firebase.apps.length) { firebase.initializeApp(firebaseConfig); } export default firebase;
带有堆栈的错误消息:
注意:在codesandbox.io中运行此文件。尝试将文件上传到Firebase Storage,但出现错误[object Object]。我可以成功地将内容写入FireStore并确认selectedFile ...
由于Firebase存储规则,这是一个403禁止的错误。