Node.js上传Base64文件至Firebase Storage遇类型错误求助
问题分析与解决方案
这个错误的根源很明确:你在初始化Storage实例时,给keyFilename传入了一个JSON对象,但这个参数要求的是字符串类型的密钥文件路径,类型不匹配直接触发了ERR_INVALID_ARG_TYPE错误。
具体问题拆解
const key = require('../key.json')会把JSON文件解析成JavaScript对象,但Storage构造函数的keyFilename参数需要的是指向密钥文件的路径字符串(比如../key.json),而非解析后的对象。- 你的Buffer处理存在冗余转换:把base64字符串先转成binary再转utf8,最后又转回base64,这完全没必要,反而可能破坏原始数据。
- 云函数没有给客户端返回响应,会导致请求超时被终止。
修正后的完整代码
const { Storage } = require('@google-cloud/storage'); const functions = require('firebase-functions'); exports.uploadVideo = functions.https.onRequest((req, res) => { // 直接传入密钥文件的路径字符串,而非解析后的对象 const gcs = new Storage({ projectId: "<my-project-id>", keyFilename: "../key.json" }); const bucket = gcs.bucket("example.appspot.com"); const gcsname = 'test.pdf'; const file = bucket.file(gcsname); // 直接用原始base64数据创建Buffer,跳过冗余转换 const pdfdata = "xNC9YUmVmU3RtIDE1NzQ+Pg0Kc3RhcnR4cmVmDQoyMTY5DQolJUVPRg=="; const buff = Buffer.from(pdfdata, 'base64'); const stream = file.createWriteStream({ metadata: { contentType: 'application/pdf' } }); stream.on('error', (err) => { console.log("Error here", err); res.status(500).send({ error: err.message }); }); stream.on('finish', () => { console.log(`File ${gcsname} uploaded successfully`); res.status(200).send({ message: "Upload completed", filename: gcsname }); }); stream.end(buff); });
关键修改说明
- 修复
keyFilename参数:将keyFilename: key改为keyFilename: "../key.json",直接传入文件路径字符串,符合Storage构造函数的参数要求。 - 简化Buffer处理:直接用原始base64字符串调用
Buffer.from(pdfdata, 'base64'),避免冗余编码转换,保证数据正确性。 - 添加请求响应:在
error和finish事件中分别返回错误、成功响应,避免云函数因超时被终止。
这样修改后,你的代码应该就能正常将Base64编码的文件上传到Firebase Storage了。
内容的提问来源于stack exchange,提问作者Waseem Tahir
相关产品推荐
相关产品推荐

