Skip to main content

How to upload files to Firebase Storage using ReactJS

· One min read
CTO

To upload a file using ReactJS to Firebase storage, you can use the HTML element <input> and use the onChange handler to take the file and upload it directly to Firebase storage.

Make sure you've initialised your Firebase setup

import { initializeApp } from 'firebase/app';

const firebaseConfig = {
apiKey: '',
authDomain: 'your-app.firebaseapp.com',
databaseURL: 'https://something-default-rtdb.firebaseio.com',
projectId: 'project',
storageBucket: 'project.appspot.com',
messagingSenderId: '',
appId: '',
measurementId: ''
};

initializeApp(firebaseConfig);

then wherever you want to upload a file from in your app, this works...

import { getStorage, ref, uploadBytes } from 'firebase/storage';

// ...

<input
accept=".csv"
type="file"
onChange={async event => {
const file = event.target.files[0];
await uploadBytes(ref(getStorage(), file.name), file);
console.log('Uploaded', file);
}}
/>

Make sure you can write to Firebase Storage. Your rules might look like

rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow write: if true;
allow read: if false;
}
}
}