向Firebase Storage上传数组时触发byteLength读取TypeError问题
解决方案:Firebase uploadBytes 传入数组报错的问题
问题根源
TypeError: Cannot read properties of undefined (reading 'byteLength') 是因为 Firebase Storage 的 uploadBytes 方法要求第二个参数必须是 Blob、File、Uint8Array 或 Buffer(Node.js 环境) 类型的二进制数据,而你传入的是普通 JavaScript 数字数组——这类数组没有 byteLength 属性,导致 Firebase 内部处理逻辑抛出错误。
本地上传图片能正常运行,是因为你当时传入的是符合要求的 File/Blob 对象,并非普通数组。
修复步骤
1. 将普通数组转换为 Uint8Array
修改你的 UploadFile 函数,先把传入的数字数组转换成 Uint8Array(这是符合 Firebase 要求的二进制类型):
export function UploadFile(fileArray){ console.log("hello testing") const storageRef = sRef(fileStore, "/working"); // 将普通数字数组转为Uint8Array const uint8File = new Uint8Array(fileArray); uploadBytes(storageRef, uint8File) .then((snapshot) => { console.log('Uploaded a blob or file!'); }) .catch(err => { console.error('上传失败:', err); }); }
2. 校验数组合法性(可选)
为避免客户端传入非法数据(比如非数字、超出0-255范围的数值),可以添加校验逻辑:
export function UploadFile(fileArray){ console.log("hello testing") const storageRef = sRef(fileStore, "/working"); // 校验数组元素是否为合法字节值 const isValid = fileArray.every(num => typeof num === 'number' && num >= 0 && num <= 255 ); if (!isValid) { console.error('传入的数组不是合法的字节数组'); return; } const uint8File = new Uint8Array(fileArray); uploadBytes(storageRef, uint8File) .then((snapshot) => { console.log('Uploaded a blob or file!'); }) .catch(err => { console.error('上传失败:', err); }); }
3. Node.js 环境下的替代方案
如果你的后端运行在 Node.js 环境,也可以将数组转换为 Buffer 类型,效果一致:
export function UploadFile(fileArray){ console.log("hello testing") const storageRef = sRef(fileStore, "/working"); // 将数组转为Buffer const bufferFile = Buffer.from(fileArray); uploadBytes(storageRef, bufferFile) .then((snapshot) => { console.log('Uploaded a blob or file!'); }) .catch(err => { console.error('上传失败:', err); }); }
额外注意
- 确保客户端发送的数组在后端接收时没有被意外转换(比如变成字符串数组),可以在
req.body.file接收后先打印确认类型。 - 处理大数组时,Uint8Array/Buffer 的转换效率足够,但如果是超大文件,建议考虑使用
uploadBytesResumable进行断点续传。
内容的提问来源于stack exchange,提问作者Benjamin Kararic
相关产品推荐
相关产品推荐

