如何使用Google Apps Script将Firebase Storage文件转存至Google Drive?
实现Firebase Storage图片转存到Google Drive的Google Apps Script方案
1. 准备工作
- 获取Firebase项目的服务账号密钥(JSON格式),用于在GAS中访问私有存储的图片;若图片已设公开访问,可跳过此步骤。
- 在Google Drive中创建目标文件夹,记录其文件夹ID(从Drive地址栏提取)。
2. 编写转存脚本
方法一:针对公开访问的图片
如果Firebase Storage中的图片已设置公开访问权限,直接通过下载URL转存:
function transferPublicImageToDrive() { // 替换为你的配置参数 const firebaseImageUrl = "https://firebasestorage.googleapis.com/v0/b/[你的Firebase项目ID].appspot.com/o/[图片存储路径]?alt=media"; const targetFolderId = "你的Google Drive目标文件夹ID"; // 下载图片并转存到Drive const imageBlob = UrlFetchApp.fetch(firebaseImageUrl).getBlob(); DriveApp.getFolderById(targetFolderId).createFile(imageBlob); }
方法二:针对私有存储的图片
若图片为私有,需通过服务账号鉴权访问:
- 在GAS编辑器中,点击「资源」→「库」,添加OAuth2库(库ID:
1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF,选择最新版本)。 - 复制Firebase服务账号JSON内容到脚本,编写鉴权与转存逻辑:
function getFirebaseAccessToken() { const serviceAccount = { "type": "service_account", "project_id": "你的Firebase项目ID", "private_key_id": "你的私钥ID", "private_key": "-----BEGIN PRIVATE KEY-----\n你的私钥内容\n-----END PRIVATE KEY-----\n", "client_email": "你的服务账号邮箱", "client_id": "你的客户端ID", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "你的证书URL" }; const scope = "https://www.googleapis.com/auth/devstorage.read_only"; return OAuth2.createService('FirebaseStorage') .setTokenUrl('https://oauth2.googleapis.com/token') .setPrivateKey(serviceAccount.private_key) .setIssuer(serviceAccount.client_email) .setScope(scope) .getAccessToken(); } function transferPrivateImageToDrive() { // 替换为你的配置参数 const projectId = "你的Firebase项目ID"; const filePath = "存储桶中的图片路径(如images/photo.jpg)"; const targetFolderId = "你的Google Drive目标文件夹ID"; // 鉴权并下载图片 const accessToken = getFirebaseAccessToken(); const apiUrl = `https://storage.googleapis.com/storage/v1/b/${projectId}.appspot.com/o/${encodeURIComponent(filePath)}?alt=media`; const imageBlob = UrlFetchApp.fetch(apiUrl, { headers: {'Authorization': `Bearer ${accessToken}`} }).getBlob(); // 上传到Google Drive DriveApp.getFolderById(targetFolderId).createFile(imageBlob); }
3. 设置自动触发(可选)
若需自动处理新增图片,可选择以下方式:
- 定时扫描:在GAS编辑器中,点击「编辑」→「当前项目的触发器」,添加新触发器,选择转存函数并设置触发频率(如每小时、每天)。
- 实时触发:借助Firebase Cloud Functions,监听Storage的文件上传事件,调用GAS Web App URL触发转存逻辑。
注意事项
- 确保Firebase服务账号拥有「存储对象查看者」权限。
- 批量处理文件时,注意GAS的每日配额限制(如UrlFetch调用次数、Drive操作次数)。
- 包含特殊字符的文件路径需做URL编码处理。
内容的提问来源于stack exchange,提问作者user1427235
相关产品推荐
相关产品推荐

