如何在Node.js中通过Google API将Blob上传至Google Drive?
解决Node.js中Blob上传Google Drive报错
part.body.pipe is not a function的问题 问题原因
Google Drive Node.js API的media.body参数要求传入Node.js可读流(Readable Stream)或Buffer,但你当前传入的是Blob对象。Node.js环境中的Blob不具备流操作的pipe方法,因此触发该错误。此外,你将二进制docx文件转成文本的操作会损坏文件内容,完全没必要。
修复方案
直接从fetch响应中获取Buffer或可读流,替代Blob对象传入Drive API:
方案1:使用Buffer上传
修改路由代码,去掉Blob转换,改用resp.buffer()获取文件二进制数据:
app.get('/getData', async (req, res) => { // 必须添加async关键字 try { const resp = await fetch(some_url, { method: "GET", headers: { Authorization: "Bearer " + some_access_token, }, }); // 获取文件Buffer const fileBuffer = await resp.buffer(); const data = { name: 'file.docx', mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", body: fileBuffer }; const driveResponse = await uploadFileToDrive(data); console.log(driveResponse); res.json(driveResponse); } catch (err) { console.error(err); res.status(500).json({ error: err.message }); } });
方案2:使用可读流上传
如果文件较大,用流可以节省内存,直接使用fetch响应的body属性(本身就是可读流):
app.get('/getData', async (req, res) => { try { const resp = await fetch(some_url, { method: "GET", headers: { Authorization: "Bearer " + some_access_token, }, }); // 直接获取响应的可读流 const fileStream = resp.body; const data = { name: 'file.docx', mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", body: fileStream }; const driveResponse = await uploadFileToDrive(data); console.log(driveResponse); res.json(driveResponse); } catch (err) { console.error(err); res.status(500).json({ error: err.message }); } });
保留原uploadFileToDrive函数(无需修改)
两种方案的body参数都符合Drive API要求,函数可以直接使用:
async function uploadFileToDrive(data) { try { const authClient = await authorize(); const response = await drive.files.create({ requestBody: { name: data.name, mimeType: data.mimeType, }, media: { mimeType: data.mimeType, body: data.body, // 支持Buffer或Node.js可读流 }, auth: authClient, }); console.log(response.data); return response.data; } catch (error) { console.log(error.message); throw error; // 抛出错误让上层路由处理 } }
额外注意点
- 原路由代码遗漏了
async关键字,必须添加才能使用await。 - 不要将二进制docx文件转成文本(
dataBlob.text()),这会破坏文件结构导致无法正常打开。
内容的提问来源于stack exchange,提问作者Shreyas Shrawage
相关产品推荐
相关产品推荐

