我正在嘗試使用 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>
在從 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 包。您可以查看他們的升級指南以獲取更多信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句