我是第一次使用 js,我不知道为什么我的代码不起作用。也许有人可以帮助我:
<!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>
我尝试了不同的方法,但我无法独自完成。我之前成功将图片上传到存储,但是后来我无法将图片的url和实时数据库中的标签保存下来。
这是浏览器控制台中的错误:
project.html:59未捕获的ReferenceError:uploadImage未定义
在 HTMLButtonElement.onclick (project.html:59:146)
您可以尝试以下代码:
从“https://www.gstatic.com/firebasejs/10.9.0/firebase-app.js”导入{initializeApp}; 从“https://www.gstatic.com/firebasejs/10.9.0/firebase-database.js”导入{ getDatabase,ref,set }; 从“https://www.gstatic.com/firebasejs/10.9.0/firebase-storage.js”导入{ getStorage,ref as refStorage,uploadBytes,getDownloadURL }; 常量 firebaseConfig = { // 您的 Firebase 配置 }; 常量应用=initializeApp(firebaseConfig); const db = getDatabase(应用程序); const 存储 = getStorage(app); 异步函数 uploadImage(){ const file = document.getElementById('photo').files[0]; const label = document.getElementById('label').value; const storageRef = refStorage(storage, 'images/' + file.name); 等待 uploadBytes(storageRef, file).then(async (snapshot) => { console.log('文件已上传'); const downloadURL = 等待 getDownloadURL(storageRef); console.log('文件位于', downloadURL); const dbRef = ref(db, '图像/' + 标签); 设置(dbRef,{ 名称:标签, url: 下载地址 }); }); } // 将函数附加到窗口对象 window.uploadImage = uploadImage;此外,请确保您的按钮标签正确关闭,如下所示: 上传