Go to Firebase console -> Storage -> allow test mode(if you want to read and write)
create a react app
Create a file firebase/firebase.utils.js
import firebase from 'firebase/app'
import 'firebase/storage'
// copy config from firebase web app project
const config={
apiKey: "your api key",
authDomain: "auth domain",
projectId: "web app name",
storageBucket: "storage bucket",
messagingSenderId: "sender ID",
appId: "app id",
measurementId: "measure id"
};
export const app=firebase.initializeApp(config)
export default firebase;
Go to App.js
import {app} from './firebase/firebase.utils.js'
function App() {
const onChange = (e) => {
const file = e.target.files[0];
const storageRef = app.storage().ref()
const fileRef = storageRef.child(file.name)
fileRef.put(file).then(() => {
console.log("Uploaded a file")
})
}
return (
<input type="file" onChange={onChange}/>
);
}
export default App;
In this if you want download link to firebase file then apply following changes to onChange
Note-> Allow read access to firebase storage using allow read: if true;
const onChange = (e) => {
const file = e.target.files[0];
const storageRef = app.storage().ref()
const fileRef = storageRef.child(file.name)
fileRef.put(file).then(() => {
fileRef.getDownloadURL().then(function (url) {
console.log(url);
});
console.log("Uploaded a file")
})
}
Rules
If you want to limit upload size to firebase go to rules under storage and use the following rules:
//this rule will allow uploading any files upto 10mb
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read: if true;
allow write: if request.resource.size < 10 * 1024 * 1024;
}
}
}
If you want to allow only images
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read: if true;
allow write: if request.resource.size < 10 * 1024 * 1024
&& request.resource.contentType.matches('image/.*');
}
}
}
If you only want write access
delete allow read: if true;