Home > OS >  How do I upload images to Firebase, with CDN and version 9.5.0?
How do I upload images to Firebase, with CDN and version 9.5.0?

Time:11-29

I'm trying to upload an image through JavaScript, with Firebase Storage. But, i can't find the method to upload the files on version 9.5.0, using the CDN (<script type="module">)

I've searched around the documenntation, and I found "storageRef.put", but, it gives me Uncaught TypeError: storage.put is not a function on the console.

Can someone help me? JavaScript code:

import { getStorage, ref } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-storage.js";

const storage = getStorage(app);
const storageRef = ref(storage);

function submit() {
    const file = document.getElementById("file").files[0];

    storageRef.put(file);
}

document.getElementById("submit").addEventListener("click", submit);

HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/firebase/8.2.2/firebase-app.min.js"></script>
<input type="file" id="file"><br><br>
<button id="submit">Enviar</button>

CodePudding user response:

In the change from Firebase v8 (namespaced) to v9 (modular) they had an overhaul of the SDK. Version 9 is not a drop in replacement for v8.

In your code I'm seeing v8 in the HTML and v9 in the javascript.

So using only v9, the example from their docs:

<script type="module">
  // Import the functions you need from the SDKs you need
  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-app.js";
 import { getStorage, ref, uploadBytes  } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-storage.js";


  // Your web app's Firebase configuration
  // For Firebase JS SDK v7.20.0 and later, measurementId is optional
  const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
  };

  // Initialize Firebase
  const firebaseApp = initializeApp(firebaseConfig);
    
  // Get a reference to the storage service, which is used to create references in your storage bucket
  const storage = getStorage(firebaseApp);
  const storageRef = ref(storage, 'some-child');
    
  // 'file' comes from the Blob or File API
  const file = document.getElementById("file").files[0];
  uploadBytes(storageRef, file).then((snapshot) => {
    console.log('Uploaded a blob or file!');
  });
</script>

As a note, you can use v9 with v8 syntax but you need to pull in the compat packages as well. You can check their upgrade guide for more information.

  • Related