如何使用CDN和9.5.0版本将图像上传到Firebase



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

我搜索了一下文档,发现";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>

在从Firebase v8(命名空间(到v9(模块化(的更改中,他们对SDK进行了全面检查版本9不是v8的替代品。

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

所以只使用v9,他们文档中的例子:

<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语法,但也需要引入compat包。您可以查看他们的升级指南以了解更多信息。