Tell us what’s happening:
I decided to use Firebase for all 5 “Api and Microservice” - projects to get a “real world experience” instead of using Glitch + MongoDb.
Your code so far
I finished all 5 projects and let you have a look at the last one.
Working solution on Google Firebase (Hosting + Storage):
There is one big issue with my solution:
I am quiet sure to not send a “formData” object. Hopefully you dont mind or correct it :)))
I used a “create-react-app” and coded everything as simple as possible:
App.js (will be attached to the Div(root) by index.js):
import React from 'react';
import Upload from './component/upload';
function App() {
return (
<div className="App">
<h1>file metaservice</h1>
<Upload />
</div>
);
}
export default App;
upload.js (this component includes everything except of the Firebase init):
import React, { Component } from "react";
import Firebase from "./firebase";
class Upload extends Component {
constructor(props) {
super(props);
this.state = {
file: "",
};
this.setFileState = this.setFileState.bind(this);
this.fileUpload = this.fileUpload.bind(this);
}
setFileState = (e) => {
this.setState({ [e.target.name]: e.target.files[0] });
};
fileUpload = (e) => {
e.preventDefault();
// if no file is selected
if (!this.state.file) {
console.log("please select a file");
} else {
// send file to the database
const storageRef = Firebase.db.ref('fileupload/' + this.state.file.name);
storageRef.put(this.state.file);
storageRef.getMetadata().then(res => {
document.getElementById('fileDiv').innerText = 'fileName: ' + res.name + ', fileSize: ' + res.size + "b"
})
}
};
render() {
return (
<div id="fileDiv">
<form>
<label>
<input type="file" name="file" onChange={this.setFileState} />
</label>
<br />
<input type="submit" value="Submit" onClick={this.fileUpload} />
</form>
</div>
);
}
}
export default Upload;
and the firebase.js (to init Firebase):
import app from "firebase/app";
import "firebase/storage";
const firebaseConfig = {
my firebaseConfig - data ...
};
class Firebase {
constructor() {
app.initializeApp(firebaseConfig);
this.db = app.storage();
};
};
export default new Firebase();
package.json (dependencies):
{
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1",
"firebase": "*"
}
Please let me know if you like it and if you think my solution should be accepted :))
Like it, subscribe it, share it, use it … whatever :)))
If you have any questions, feel free to ask!
Dont forget to like it
Best regards