Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

352
Visualizações
How to upload text file on Google drive?

How can I upload text file on Google drive using CloudFunctions?

File has been created on local folder but not sure how can I pass this in metadata body.

I have followed below approach:

Step 1: Write file

// Write file
fs.writeFileSync("sample.txt", "Hello content!");

Step 2: Prepare metadata


    const metadata = {
      name: "sample.txt",
      parents: [parentFolder],
      mimeType: "text/plain",
      uploadType: "media",
    };

Step 3: Call Google drive API to upload file

    axios({
      method: "POST",
      url: "https://www.googleapis.com/drive/v3/files?supportsAllDrives=true",
      headers: {
        Authorization: `Bearer ${token}`,
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      data: metadata,
    })
      .then((res) => {
        response.status(200).send(res.data);
      })
      .catch((err) => {
        response.status(500).send(err.message);
      });

So whole function code is:

exports.onCreateFile = functions.https.onRequest((request, response) => {
  // <-- Some validation -->
    const parentFolder = request.query.parentFolder;
    if (!parentFolder) {
      response.status(400).send("Parent folder not found");
      return;
    }

    // Write file
    fs.writeFileSync("vault.txt", "Hello content!");

    const metadata = {
      name: "vault.txt",
      parents: [parentFolder],
      mimeType: "text/plain",
      uploadType: "media",
    };

    axios({
      method: "POST",
      url: "https://www.googleapis.com/drive/v3/files?supportsAllDrives=true",
      headers: {
        Authorization: `Bearer ${token}`,
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      data: metadata,
    })
      .then((res) => {
        // console.log(res.data);
        response.status(200).send(res.data);
      })
      .catch((err) => {
        // console.log(err);
        response.status(500).send(err.message);
      });
});

Basically Mobile app will call CloudFunction by passing accessToken and parentFolderId and cloudFunction will upload file after some business logic.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can not pass the file as metadata. Instead you can pass it as form data like this:

    const metadata = { name: "sample.txt", mimeType: "text/plain", parents: ["root"] };
    const fileContent = "Hello content!";
    const fileBlob = new Blob([fileContent], {type: "text/plain"});
    const form = new FormData();
    form.append("metadata", JSON.stringify(metadata), { type: "application/json" }));
    form.append("file", fileBlob);
    fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&supportsAllDrives=true", {
      method: "POST",
      headers: new Headers({ Authorization: `Bearer ${token}` }),
      body: form,
    });
over 4 years ago · Santiago Trujillo Relatório

0

Finally, it got resolved using the following approach:

fs.writeFileSync("/tmp/sample.txt", "Hello Temp content!");

    const metadata = {
      name: "sample.txt",
      mimeType: "text/plain",
      parents: [parentFolder],
    };

    const formData = new FormData();
    formData.append("metadata", JSON.stringify(metadata), {
      contentType: "application/json",
    });
    formData.append("file", fs.createReadStream("/tmp/sample.txt"));

    axios({
      method: "POST",
      url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&supportsAllDrives=true",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": `multipart/related; boundary=${formData.getBoundary()}`,
      },
      data: formData,
    })
      .then((res) => {
        response.status(200).send(res.data);
      })
      .catch((err) => {
        response.status(500).send(err);
      });

This Link helped to resolve this issue.

Posted on behalf of the question asker

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda