NodeJS环境下Google Cloud Storage分片图片上传文件为0字节问题咨询
问题根因
你上传后得到0字节文件的核心原因有两个:
- 仅创建了GCS的写入流,没有将
multiparty返回的part可读流的数据传输到写入流中 - 没有将流上传过程封装为Promise,外层
await没有等待上传完成就提前返回了响应,导致流写入过程被中断
正确的GCS分片/流式上传实现
你可以直接参考下面的GCSService.uploadFile方法实现,逻辑和你之前用的Azure uploadStream完全对齐:
const { Storage } = require('@google-cloud/storage'); // 初始化GCS实例,确保已经配置好服务账号密钥等认证信息 const storage = new Storage(); const GCSService = { uploadFile: async (bucketName, readStream, blobName, contentType, originalFileName) => { const bucket = storage.bucket(bucketName); const targetFile = bucket.file(blobName); // 将流写入过程封装为Promise,方便外层await等待完成 return new Promise((resolve, reject) => { const writeStream = targetFile.createWriteStream({ // 大于10MB的文件建议开启可续传,GCS会自动完成分片、并发上传、重试逻辑 resumable: true, // 对应Azure的4MB分片大小配置 chunkSize: 4 * 1024 * 1024, contentType: contentType, // 可自定义文件元数据 metadata: { originalName: originalFileName } }); // 核心步骤:将读取到的文件流pipe到GCS写入流 readStream.pipe(writeStream); // 监听上传完成事件,返回文件信息 writeStream.on('finish', async () => { const [fileMetadata] = await targetFile.getMetadata(); resolve({ fileUrl: `https://storage.googleapis.com/${bucketName}/${blobName}`, size: fileMetadata.size, contentType: fileMetadata.contentType, fileName: blobName }); }); // 监听上传错误 writeStream.on('error', (uploadErr) => { console.error('GCS文件上传失败:', uploadErr); reject(uploadErr); }); }); } }
注意事项
- 如果上传的文件普遍小于10MB,可以把
resumable设为false减少请求开销 - GCS的可续传上传已经内置了分片管理、失败重试逻辑,不需要像Azure一样手动配置并发数,SDK会自动处理
- 不需要额外处理流的销毁逻辑,
pipe方法会在传输完成或出错后自动销毁流资源
内容的提问来源于stack exchange,提问作者Varun Joshi
相关产品推荐
相关产品推荐

