'Upload image to Firebase 9 storage with React?
I'm trying to make a simple input button that users can click to upload image (.png) files to Firebase-Storage (v.9) with React (for non-authenticated users).
Here is the component:
import { useState } from 'react';
import { storage } from './firebase.config';
import { ref, uploadBytes } from 'firebase/storage';
console.log(storage); // getting the storage object
export default function Upload() {
const [img, setImg] = useState(null);
const [imgError, setImgError] = useState(null);
// handle submit
const handleSubmit = async e => {
e.preventDefault();
const uploadPath = `images/${img.name}`; // geting the image path
const storageRef = ref(storage, uploadPath); // getting the storageRef
uploadBytes(storageRef, img)
.then(snapshot => console.log(snapshot))
.catch(err => console.log(err.message));
};
// handle upload
const handleUpload = e => {
setImgError(null);
let selected = e.target.files[0];
if (!selected) {
setImgError('Please select file');
return;
}
if (!selected.type.includes('image')) {
setImgError('Please select image file');
return;
}
if (selected.size > 1000000) {
setImgError('Please select smaller file size');
return;
}
setImgError(null);
setImg(selected);
};
return (
<div>
<h1>Upload component</h1>
<form onSubmit={handleSubmit}>
<label>
<span>Select image file</span>
<input type='file' onChange={handleUpload} required />
</label>
<button>Add to storage</button>
{setImgError && <p>{imgError}</p>}
</form>
</div>
);
}
And here is the Firebase config file.
import { initializeApp } from 'firebase/app';
import { getStorage } from 'firebase/storage';
const firebaseConfig = {
apiKey: 'here is the key',
authDomain: 'here is the authDomain',
projectId: 'here is the project ID',
storageBucket: 'here is the storageBucket',
messagingSenderId: 'here is the messagingSenderId',
appId: 'here is appId',
};
// init App
const firebaseApp = initializeApp(firebaseConfig);
// init Storage
export const storage = getStorage(firebaseApp);
And here is Firebase-Storage rules file.
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
And, yet, it doesn't work. I try to google the error messege, but could find the solution.
Firebase Storage: An unknown error occurred, please check the error payload for server response. (storage/unknown) Bad Request
I followed these docs: https://firebase.google.com/docs/storage/web/upload-files
Solution 1:[1]
Had something similar today.
I solved it by manually creating the parent folder. In your case I suggest you create the images
folder first and then rerun the code.
Good luck!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |