【问题标题】:How to upload text file on Google drive?如何在谷歌驱动器上上传文本文件?
【发布时间】:2021-10-22 10:59:33
【问题描述】:

如何使用 CloudFunctions 在 Google 驱动器上上传文本文件?

文件已在本地文件夹中创建,但不知道如何在元数据正文中传递它。

我遵循以下方法:

第 1 步:写入文件

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

第 2 步:准备元数据


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

第 3 步:调用 Google Drive API 上传文件

    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);
      });

所以整个函数代码是:

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);
      });
});

基本上移动应用会通过传递accessToken和parentFolderId来调用CloudFunction,而cloudFunction会在一些业务逻辑之后上传文件。

【问题讨论】:

  • 云函数在哪里?
  • @MartinZeitler 我已经更新了描述。

标签: node.js firebase google-cloud-functions google-drive-api


【解决方案1】:

最后通过以下方法解决了:

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);
      });

这个Link 帮助解决了这个问题。

代表提问者发帖

【讨论】:

    【解决方案2】:

    您不能将文件作为元数据传递。相反,您可以将其作为表单数据传递,如下所示:

        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,
        });
    

    【讨论】:

    • 它返回 400,现在尝试分段上传,但没有运气。 const form = new FormData(); form.append("file", "Some dummy text"); axios({ method: "POST", url: "https://www.googleapis.com/drive/v3/files?uploadType=multipart&amp;supportsAllDrives=true", headers: { Authorization: Bearer ${token}, Accept: "application/json", "Content-Type": multipart/form-data;边界=${form.getBoundary()} , }, data: form, }) .then((res) =&gt; { response.status(200).send(res.data); })
    • 您没有将元数据附加到表单。尽量靠近我发布的示例代码。因为代码有效。
    • 它正在工作,但在我的情况下有两个问题,也许您可​​以提供帮助:1:Node 中没有 Blob,我正在使用 fs.writeFileSync("/tmp/vault.txt", "Hello Temp content!"); 编写文件。附加元数据抛出ReferenceError: Blob is not defined 2:上传的“无标题”文本文件有----------------------------866368930733703415619015 Content-Disposition: form-data; name="file"; filename="vault.txt" Content-Type: text/plain Hello Temp content! ----------------------------866368930733703415619015--
    • 我更新了我的答案。看看它是否工作。不幸的是我无法测试它。如果它不起作用,请告诉我。你也可以试试blobstackoverflow.com/a/58896208/7821823
    • 谢谢。我很高兴它得到了解决,并且我已经通过更新更新了我的问题。 link 帮助解决了这个问题。标头应该是{ Authorization: Bearer ${token}, "Content-Type": multipart/related;边界=${formData.getBoundary()}, }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多