Google 驱动器 API 没有将正文写入文件

Google Drive API Not Writing Body To File

我一直在尝试使用浏览器的 Google API 创建文件。我重用了过去用于与来自 NodeJS 的 api 通信的一些代码,并将其重新用于浏览器。

const content = "this is some content";

const fileMetadata = {
  name: "my-file.txt",
  alt: "media",
};

const media = {
  mimeType: "text/plain",
  body: content,
};

const {
  result: { id: fileId },
} = await gapi.client.drive.files.create({
  resource: fileMetadata,
  media: media,
  fields: "id",
});

我通常会收到一个成功的响应,说我的文件已创建。

但是,当我尝试获取文件的内容时,body 字段是一个空字符串。

const { body } = await gapi.client.drive.files.get({
  fileId: fileId,
});

console.log(body)
// ""

我认为创建文件的请求可能格式不正确,但它在后端运行时可以正常工作,所以我很困惑为什么它在浏览器中不起作用。

文件的主体应该是流的形式。不是纯文本。

var media = {
  mimeType: 'text/plain',
  body: fs.createReadStream('files/my-file.txt')
};

至于console.log(body)

另外 file.get returns 一个 file.resource 文件资源不提供查看文件内容的选项。 Google 驱动器本身无法读取文件,它只能告诉您有关文件的信息。

您提到您正在为浏览器使用 Google API,而不是 node.js。

我建议直接针对 Google REST API 发送请求,因为 gapi.client.drive.create() 发送实际的二进制文件似乎有问题(发送元数据似乎有效) .看这里,例如:, or

您可以将数据作为 blob 发送并使用 FormData class 创建请求。

  async upload(blob, name, mimeType, parents = ["root"]) {
    const metadata = { name, mimeType, parents };
    const form = new FormData();
    form.append("metadata", new Blob([JSON.stringify(metadata)], { type: "application/json" }));
    form.append("file", blob);
    return fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&supportsAllDrives=true", {
      method: "POST",
      headers: new Headers({ Authorization: `Bearer ${gapi.auth.getToken().access_token}` }),
      body: form,
    });
  }

我没有测试过你是否可以发送 String 而不是 Blob,但你可以轻松地从 String 创建一个 Blob:

const content = "this is some content";
const blob = new Blob([content], { type: 'text/plain' });