Firebase Cloud Storage下载报错‘no such object’:exists返回true但下载失败
问题:Firebase云存储exists返回true,但下载文件时报“不存在对象”错误
我在Firebase Cloud Function中使用TypeScript代码从Firebase Cloud Storage下载文件时遇到异常:调用exists()方法返回true,但执行download()或createReadStream()时却抛出“no such object”错误。
原始下载代码:
exports.getProfileImage = functions.https.onRequest(async (req, resp) => { const authHeader = req.headers.authorization; if (!authHeader || !authHeader.startsWith("Bearer ")) { resp.status(401).send("Unauthorized"); return; } let detail = "start"; let decodedToken: DecodedIdToken; try { const idToken = authHeader.split("Bearer ")[1]; try { decodedToken = await admin.auth().verifyIdToken(idToken); } catch (e) { resp.status(401).send("Unauthorized"); return; } const match = RegExp("^\/(\w+)$").exec(req.path); const uid = match && match[1]; if (!uid) { resp.status(400).send(`Invalid profile image request: ${req.path}`); return; } const filePath = `user/${uid}/profileImage`; detail = `locating file ${filePath}`; const ref = admin.storage().bucket().file(filePath); detail = "Checking file exists"; if (!await ref.exists()) { resp.status(404).send(`Requested profile image not found: ${req.path}`); return; } detail = `Downloading profile image for ${decodedToken.email} ` + `from ${ref.cloudStorageURI.href}`; const [fileContent] = await ref.download(); resp.type("jpeg"); detail = "Sending result"; resp.send(fileContent); return; } catch (e) { if (e instanceof Error) { resp.status(500).send(`Error while retrieving image: ${e.message}.` + `Occurred during ${detail}`); } else { resp.status(500).send("Unknown error retrieving image"); } } });
替换为createReadStream后仍出现类似错误:
detail = `Downloading profile image for ${decodedToken.email} ` + `from ${ref.cloudStorageURI.href}`; const fileReader = ref.createReadStream(); detail = "Setting type to jpeg"; resp.type("jpeg"); detail = "Piping file content to response"; fileReader.on("error", (err) => resp.status(500).send(err.message)) .pipe(resp); detail = "Sending result"; return;
可能的原因及解决办法
存储桶不匹配
云函数默认调用的存储桶可能并非你存储文件的目标桶。检查代码中是否明确指定了正确的存储桶名称,比如:const ref = admin.storage().bucket("your-specific-bucket.appspot.com").file(filePath);确保桶名称与文件实际所在的存储桶完全一致,包括区域后缀(如果使用了非默认区域的桶)。
文件路径大小写敏感问题
Cloud Storage的文件路径是严格区分大小写的。确认filePath的大小写与存储桶中实际文件的路径完全一致,避免因大小写差异导致下载时找不到对象。对象状态异常
极少数情况下,exists()仅验证对象元数据存在,但实际文件内容已被移除或处于不可访问状态。可以直接在Firebase控制台检查该路径下的文件是否确实存在且能正常打开。UID正则匹配缺陷
Firebase的UID允许包含连字符(-),但你代码中使用的RegExp("^\/(\w+)$")里的\w不匹配连字符。如果后续遇到含连字符的UID,会导致路径错误。建议修改正则以兼容所有合法UID:const match = RegExp("^\/([\\w-]+)$").exec(req.path);
内容的提问来源于stack exchange,提问作者BlueMonkMN
相关产品推荐
相关产品推荐

