Google Drive API v3提取Blob上传Firebase Storage报byteLength错误处理
根因分析
Node.js 环境下 googleapis 包返回的 Blob 是非标准实现,内容存储在 Symbol 类型的私有属性中,没有实现标准 Blob 的 size、arrayBuffer() 等接口,Firebase Storage 的 uploadBytes 方法读取内容字节长度时无法获取到有效属性,因此抛出 byteLength 未定义的报错。
你提到的 const file = new Blob([response.data.buffer], {type: response.data.type}) 写法不可行,因为 buffer 是私有属性,直接通过 . 访问拿到的是 undefined。
正确实现方案
方案1:直接获取 Buffer 上传(更推荐,Node.js 环境下性能最优)
修改请求的 responseType 为 arraybuffer,拿到的响应数据直接转成 Buffer 即可上传,无需构造 Blob:
drive.files.get({ fileId: fileId, alt: 'media', }, {responseType: 'arraybuffer'}) .then(response => { const fileBuffer = Buffer.from(response.data); const storage = getStorage(); const storageRef = ref(storage, 'testvideo.mp4'); // 可选指定contentType,不指定也可以自动识别 uploadBytes(storageRef, fileBuffer, { contentType: 'video/mp4' }) .then((snapshot) => { console.log('Uploaded a buffer!'); }); }) .catch(err=>{ console.log(err); });
方案2:构造标准 Blob 上传(适配需要 Blob 类型的场景)
先将返回的非标准 Blob 转成 ArrayBuffer,再构造标准 Blob 对象即可:
drive.files.get({ fileId: fileId, alt: 'media', }, {responseType: 'blob'}) .then(async response => { // 先转成标准ArrayBuffer const arrayBuffer = await response.data.arrayBuffer(); const file = new Blob([arrayBuffer], { type: response.data.type }); const storage = getStorage(); const storageRef = ref(storage, 'testvideo.mp4'); uploadBytes(storageRef, file) .then((snapshot) => { console.log('Uploaded a blob!'); }); }) .catch(err=>{ console.log(err); });
内容的提问来源于stack exchange,提问作者Kopwithit
相关产品推荐
相关产品推荐

