• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

278
Views
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.

about 3 years ago · Santiago Trujillo
2 answers
Answer question

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,
    });
about 3 years ago · Santiago Trujillo Report

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

about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error