向Google Drive API上传Buffer时出现TypeError: part.body.pipe is not a function错误
解决Google Drive上传Buffer时报
TypeError: part.body.pipe is not a function的问题 报错原因
Google Drive Node.js客户端的drive.files.create方法里,media.body参数要求传入可读流(Readable Stream),不能直接传Buffer对象。客户端内部会调用流的pipe方法处理上传逻辑,而Buffer没有这个方法,所以触发了报错。本地文件能正常上传,是因为读取本地文件时一般用fs.createReadStream()这类返回可读流的方法,天然符合客户端要求。
修复方案
把转换后的Buffer包装成可读流再传入即可,用Node.js内置的stream模块就能实现:
- 先引入
stream模块:
const { Readable } = require('stream');
- 修改上传代码,将Buffer转为可读流:
const templateBuffer = Buffer.from(order.template.split(',')[1], 'base64'); // 将Buffer转换为可读流 const templateStream = Readable.from(templateBuffer); await drive.files.create({ resource: { name: 'template.png', parents: [pedidoFolderId], }, media: { mimeType: 'image/png', body: templateStream // 替换为可读流 }, });
额外提示
如果是处理大文件,建议直接用流式读取/转换的方式,避免把整个文件加载到内存里(比如从网络获取数据时直接传递流);但对于图片这类小文件,转换Buffer为可读流的方式完全够用。
内容的提问来源于stack exchange,提问作者Rodrigo Valle
相关产品推荐
相关产品推荐

