使用JavaScript上传至Firebase失败,uploadImage未定义错误求助
Firebase代码报错排查:uploadImage未定义
我首次使用JavaScript开发,不清楚代码为何无法运行,恳请帮忙排查。此前我曾成功将图片上传至Firebase Storage,但无法将图片URL和标签保存至Realtime Database。当前浏览器控制台报错:
project.html:59 Uncaught ReferenceError: uploadImage is not defined
at HTMLButtonElement.onclick (project.html:59:146)
我的代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/uikit.css"> <link rel="stylesheet" href="css/styles.css"> <script src="js/uikit.js"></script> <script src="js/uikit-icons.js"></script> <title>Face Recognition</title> </head> <body> <section> <a href="index.html">Back to home</a> </section> <input type="text" id="label" placeholder="Input name"/></br> <input type="file" id="photo"/></br> <button id="upload" onclick="uploadImage()"></button> <script type="module"> import { initializeApp } from "https://www.gstatic.com/firebasejs/10.9.0/firebase-app.js"; import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/10.9.0/firebase-database.js"; import { getStorage, ref as refStorage, uploadBytes, getDownloadURL } from "https://www.gstatic.com/firebasejs/10.9.0/firebase-storage.js"; const firebaseConfig = { my firebase config...; }; const app = initializeApp(firebaseConfig); const db = getDatabase(app); const storage = getStorage(app); async function uploadImage(){ const file = document.getElementById('photo').files[0]; const label = document.getElementById('label').value; const storageRef = refStorage(storage, 'images/' + file.name); await uploadBytes(storageRef, file).then(async (snapshot) => { console.log('File uploaded'); const downloadURL = await getDownloadURL(storageRef); console.log('File at', downloadURL); const dbRef = ref(db, 'images/' + label); set(dbRef, { name: label, url: downloadURL }); }); } </script> </body> </html>
问题原因
- 模块作用域限制:你的
<script>标签加了type="module",ES模块内部的函数默认不会暴露到全局作用域,所以HTML里的onclick="uploadImage()"找不到这个函数。 - 按钮标签语法错误:按钮标签
<button id="upload" onclick="uploadImage()"缺少闭合的>,属于无效HTML。
修复方案
1. 修复按钮语法错误
把按钮标签补全,同时建议加上按钮文本:
<button id="upload" onclick="uploadImage()">上传图片</button>
2. 解决函数找不到的问题(选一种即可)
方案一:将函数挂载到全局
在模块内的uploadImage函数定义后,添加一行代码把函数暴露到window对象:async function uploadImage(){ // 原有函数内容... } // 新增这行 window.uploadImage = uploadImage;方案二:用事件监听替代内联onclick(推荐)
先移除按钮上的onclick属性:<button id="upload">上传图片</button>然后在模块内添加事件监听代码:
async function uploadImage(){ // 原有函数内容... } // 新增事件监听 document.getElementById('upload').addEventListener('click', uploadImage);
3. 额外优化(可选)
给uploadImage函数加基础输入校验,避免用户未选择文件或未输入标签时出错:
async function uploadImage(){ const file = document.getElementById('photo').files[0]; const label = document.getElementById('label').value.trim(); if(!file) { alert('请先选择要上传的图片'); return; } if(!label) { alert('请输入名称标签'); return; } // 原有上传逻辑... }
内容的提问来源于stack exchange,提问作者xSequenic
相关产品推荐
相关产品推荐

