skip to Main Content

How do I upload images to firebase without an HTML form, I need to use code only.
I have tried some ways myself but the files fail to preview they’re corrupted I guess.
I’m developing my App in React and I need a way to upload images to firebase without an HTML form

I tried:

await uploadBytes(storageRef, '../images/image.jpg')

I also tried:
const metadata ={ contentType:'image/jpeg' }
and also

const metadata ={
  contentType:'image/svg+xml'
}
await uploadBytes(storageRef, '../images/image.jpg', metadata)

2

Answers


  1. There is no way to upload a file to Cloud Storage for Firebase with just a local path as you do here uploadBytes(storageRef, '../images/image.jpg').

    If you pass a string as the second argument, you will have to call uploadString and the second argument has to be the base64 encoded data that you want to upload.

    If you want to upload a file based on its path, you will have to either create a File reference to that file, or read its data into a Blob and then pass that to uploadBytes.

    All of these are covered in the Firebase documentation on uploading data, so I recommend keeping that handy.

    Login or Signup to reply.
  2. use the Firebase SDK for Cloud Storage and the FileReader API in JavaScript.

    import { getStorage, ref, uploadBytes } from "firebase/storage";
    
    const storage = getStorage();
    
    const handleFileUpload = (file) => {
      const storageRef = ref(storage, "images/" + file.name);
      const metadata = {
        contentType: file.type,
      };
      const reader = new FileReader();
      reader.readAsArrayBuffer(file);
      reader.onload = async (event) => {
        const buffer = event.target.result;
        await uploadBytes(storageRef, buffer, metadata);
      };
    };
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search