Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 522
Ashish Narnoli Avatar asked Jan 20 '26 22:01

Ashish Narnoli


2 Answers

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,
    });
like image 115
Mario Varchmin Avatar answered Jan 22 '26 10:01

Mario Varchmin


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

like image 34
2 revsDharman Avatar answered Jan 22 '26 10:01

2 revsDharman