I am trying to set metadata for my image but Firebase isn't taking in my custom metadata. After uploading the image I should see my metadata under 'Other Metadata'.
Below is how it's showing up for me now:
My code is as follows, you can see I am adding custom metadata to my file:
import { firebaseApp } from "./firebase";
import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
import { React} from "react";
// Initialize Firestore
const storage = getStorage(firebaseApp);
/**** PROPERTY LISTINGS ****/
// Upload 1 file to Firebase Storage
export async function uploadFile(file, houseId, houseName) {
//const storage = getStorage();
// Create the file metadata
/** @type {any} */
const metadata = {
contentType: file.type,
cacheControl: 'public,max-age=300',
customMetadata: {
houseId: houseId,
houseName: houseName,
},
};
console.log("metadata: ", metadata);
// Upload file and metadata to the object 'images/mountains.jpg'
const storageRef = ref(storage, 'property_images/' houseId '/' file.name, metadata);
const uploadTask = uploadBytesResumable(storageRef, file);
// Listen for state changes, errors, and completion of the upload.
uploadTask.on('state_changed',
(snapshot) => {
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' progress '% done');
switch (snapshot.state) {
case 'paused':
console.log('Upload is paused');
break;
case 'running':
console.log('Upload is running');
break;
}
},
(error) => {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
// ...
case 'storage/unknown':
// Unknown error occurred, inspect error.serverResponse
break;
}
},
() => {
// Upload completed successfully, now we can get the download URL
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
console.log('File available at', downloadURL);
});
}
);
}
I am even checking the metadata on my console and it's coming out at follows, so I know there are values being passed in:
Below are my firestore storage rules:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
//this is the part we changed...
allow read, write: if true;
}
}
}
CodePudding user response:
The problem is here:
const storageRef = ref(storage, 'property_images/' houseId '/' file.name, metadata);
You're passing the metadata to the ref
function, which is not an expected argument for that function.
You'll instead want to pass the metadata to the call to uploadBytesResumable
, which does accept a metadata argument