xrd*_*xrd 1 javascript google-cloud-storage firebase reactjs create-react-app
我正在尝试从我的React应用程序中将文件写入云存储。我使用create-react-app工具创建了一个新的React应用。我相信我已经按照正确的说明获取了存储参考,并带有以下代码:this.storage = firebase.storage();。但是,无论我如何配置firebase和导入什么,我都会看到此错误:TypeError: _this.firebase.storage() is not a function.。
我尝试导入@firebase/storage(在此处注释),但是这会导致错误,并且该模块的NPM页面表明这不是用户应该直接加载的内容。
我相信我添加了适当的firebase库。我可以使用firestore和旧版数据库(我删除了代码来做到这一点,但是如果使用,它就可以工作this.firestore = this.firebase.firestore();)。但是,存储尚未解决。
对于是否应该使用客户端库进行云存储,我还不清楚(我相信这与Firebase的“存储”完全一样)。但是,所有示例似乎都是用于从NodeJS应用访问存储的,而我想从浏览器上下文中将文件编写为客户端JavaScript。
我的package.json看起来像这样:
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@firebase/app": "^0.3.2",
"@firebase/auth": "^0.5.2",
"@firebase/firestore": "^0.5.6",
"@material-ui/core": "^1.3.1",
"@material-ui/icons": "^1.1.0",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"react": "^16.4.1",
"react-dom": "^16.4.1"
},
"scripts": {
"start": "PORT=3009 react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
Run Code Online (Sandbox Code Playgroud)
我的index.js样子是这样的:
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import firebase from '@firebase/app';
import '@firebase/firestore';
import '@firebase/auth';
//import '@firebase/storage';
var config = {
apiKey: "ABCDEFG",
authDomain: "abcdefg.firebaseapp.com",
databaseURL: "https://abcdefg.firebaseio.com",
projectId: "abcdefg",
storageBucket: "abcdefg.appspot.com",
messagingSenderId: "12345"
};
firebase.initializeApp(config);
class Index extends Component {
constructor(props) {
super(props);
this.state = {};
this.firebase = firebase;
this.firestore = this.firebase.firestore(); // This works fine.
this.storage = this.firebase.storage(); // This fails
console.log( "Got storage ref" );
}
render() {
return (
<div>
Hello
</div>
)
}
}
ReactDOM.render(
<Index/>,
document.getElementById('react-container')
);
Run Code Online (Sandbox Code Playgroud)
firebase配置是从Firebase控制台复制的(但此处已更改)。
这工作:$ npm i @firebase/storage --save。
当前结果在"@firebase/storage": "^0.2.3"inside package.json。
如果有,我可以在firebaseConfig.js文件中使用如下代码在firebase中设置存储:
import firebase from '@firebase/app';
import '@firebase/firestore';
import '@firebase/auth';
import '@firebase/storage';
Run Code Online (Sandbox Code Playgroud)
然后像这样的代码工作:
const storage = firebase.storage();
const files = [ 'image1.png', 'image2.png' ];
files.map( filename => {
storage
.ref( `/covers/${filename}` )
.getDownloadURL()
.then( url => {
console.log( "Got download url: ", url );
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2721 次 |
| 最近记录: |