如何在MediaRecorder应用中自动将音视频存储到Firebase Storage?
实现录制文件自动上传Firebase Storage的方案
步骤1:补充Firebase必要导入
你当前的Firebase模块导入缺少上传文件的核心方法,需在导入语句中添加uploadBytes:
import { getStorage, ref, uploadBytes } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-storage.js";
步骤2:简化Firebase初始化代码
删除冗余的引用定义,只保留全局可用的存储文件夹引用,方便后续调用:
// Initialize Firebase const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app); const storage = getStorage(app); // 传入app实例确保初始化正确 const mediaFolderRef = ref(storage, 'medias'); // 指向Storage中的medias文件夹 // 暴露给全局,让script.js能访问 window.mediaFolderRef = mediaFolderRef;
步骤3:在录制完成后添加上传逻辑
修改makeLink函数,在生成本地下载链接的同时,将录制好的Blob文件上传到Firebase:
function makeLink(){ let blob = new Blob(chunks, {type: media.type }) , url = URL.createObjectURL(blob) , li = document.createElement('li') , mt = document.createElement(media.tag) , hf = document.createElement('a') , fileName = `${counter++}${media.ext}`; // 动态生成文件名 ; mt.controls = true; mt.src = url; hf.href = url; hf.download = fileName; hf.innerHTML = `download ${hf.download}`; li.appendChild(mt); li.appendChild(hf); ul.appendChild(li); // 上传文件到Firebase Storage const fileRef = ref(window.mediaFolderRef, fileName); uploadBytes(fileRef, blob) .then(() => { console.log(`文件 ${fileName} 上传成功`); // 可选:添加云端上传成功提示 const successTip = document.createElement('p'); successTip.textContent = `${fileName} 已同步到云端`; successTip.style.color = 'green'; li.appendChild(successTip); }) .catch(err => { console.error('上传失败:', err); // 可选:添加错误提示 const errorTip = document.createElement('p'); errorTip.textContent = `上传出错:${err.message}`; errorTip.style.color = 'red'; li.appendChild(errorTip); }); }
步骤4:配置Firebase Storage规则
默认规则禁止匿名上传,测试环境可临时修改规则(正式上线必须改回安全规则):
在Firebase控制台的「Storage > 规则」中替换为:
rules_version = '2'; service firebase.storage { match /b/{bucket}/o { match /{allPaths=**} { allow read, write: if true; // 测试用,正式环境改为`if request.auth != null;` } } }
修改后的完整代码片段
index.html(关键修改)
<script type="module"> import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js"; import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-analytics.js"; import { getStorage, ref, uploadBytes } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-storage.js"; const firebaseConfig = { apiKey: "AIzaSyCWOdeArFIfm_VrhaP_Boe0Ly7ID51aodM", authDomain: "mediarecorder-dda3b.firebaseapp.com", databaseURL: "https://mediarecorder-dda3b-default-rtdb.firebaseio.com", projectId: "mediarecorder-dda3b", storageBucket: "gs://mediarecorder-dda3b.appspot.com", messagingSenderId: "152268264978", appId: "1:152268264978:web:b6233300016d25e4f12acb", measurementId: "G-E69QHKH7LF" }; const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app); const storage = getStorage(app); const mediaFolderRef = ref(storage, 'medias'); window.mediaFolderRef = mediaFolderRef; </script>
script.js(关键修改)
function makeLink(){ let blob = new Blob(chunks, {type: media.type }) , url = URL.createObjectURL(blob) , li = document.createElement('li') , mt = document.createElement(media.tag) , hf = document.createElement('a') , fileName = `${counter++}${media.ext}`; ; mt.controls = true; mt.src = url; hf.href = url; hf.download = fileName; hf.innerHTML = `download ${hf.download}`; li.appendChild(mt); li.appendChild(hf); ul.appendChild(li); // 上传到Firebase const fileRef = ref(window.mediaFolderRef, fileName); uploadBytes(fileRef, blob) .then(() => { const successTip = document.createElement('p'); successTip.textContent = `${fileName} 已同步到云端`; successTip.style.color = 'green'; li.appendChild(successTip); }) .catch(err => { const errorTip = document.createElement('p'); errorTip.textContent = `上传出错:${err.message}`; errorTip.style.color = 'red'; li.appendChild(errorTip); }); }
额外说明
- 若需要获取上传后的文件公开访问链接,可导入
getDownloadURL方法,在uploadBytes成功后调用:import { getDownloadURL } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-storage.js"; // ... uploadBytes(fileRef, blob).then((snapshot) => { getDownloadURL(snapshot.ref).then((url) => { console.log('文件访问地址:', url); }); }); - 正式环境务必将Storage规则改为仅允许认证用户上传,避免恶意文件注入。
内容的提问来源于stack exchange,提问作者Devarshi kansara
相关产品推荐
相关产品推荐

