【问题标题】:How do I upload images to Firebase, with CDN and version 9.5.0?如何使用 CDN 和版本 9.5.0 将图像上传到 Firebase?
【发布时间】:2021-11-28 21:15:47
【问题描述】:

我正在尝试使用 Firebase 存储通过 JavaScript 上传图片。但是,我找不到使用 CDN (<script type="module">) 上传 9.5.0 版文件的方法

我搜索了文档,发现了“storageRef.put”,但是它在控制台上给了我Uncaught TypeError: storage.put is not a function

有人可以帮助我吗? JavaScript 代码:

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>

【问题讨论】:

    标签: javascript firebase file


    【解决方案1】:

    在从 Firebase v8(命名空间)到 v9(模块化)的变化中,他们对 SDK 进行了大修。 版本 9 不是 v8 的替代品。

    在您的代码中,我在 HTML 中看到 v8,在 javascript 中看到 v9。

    所以只使用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>
    

    请注意,您可以将 v9 与 v8 语法一起使用,但您还需要引入兼容包。您可以check their upgrade guide了解更多信息。

    【讨论】:

    • 好的,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-12-22
    • 2021-01-24
    • 1970-01-01
    • 2021-12-16
    • 2017-04-15
    • 2022-08-13
    • 2021-07-30
    • 2020-09-25
    相关资源
    最近更新 更多