Search code examples
javascriptgoogle-drive-api

Error: 'TypeError: part.body.pipe is not a function' when uploading Buffer to Google Drive API"


I'm trying to upload a file to a folder on Google Drive. I can successfully upload local images, but I'm having trouble uploading a Buffer.

Essentially, I receive a dataUrl as a parameter and then convert it to a Buffer so that I can send it:

const templateBuffer = Buffer.from(order.template.split(',')[1], 'base64');
await drive.files.create({
    resource: {
        name: 'template.png',
        parents: [pedidoFolderId],
    },
    media: {
        mimeType: 'image/png',
        body: templateBuffer
    },
});```

However, I'm encountering an error: TypeError: part.body.pipe is not a function.

Solution

  • In your showing script, how about the following modification?

    Modified script:

    const stream = require("stream"); // Added
    const templateBuffer = Buffer.from(order.template.split(',')[1], 'base64');
    const res = await drive.files.create({
      resource: {
        name: "template.png",
        parents: [pedidoFolderId],
      },
      media: {
        mimeType: "image/png",
        body: new stream.PassThrough().end(templateBuffer), // Modified
      },
    });
    console.log(res.data);
    
    • By this modification, when your client is valid and also the value of templateBuffer is a valid value of PNG image, the data is correctly uploaded to the folder pedidoFolderId.