You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JavaScript调用Google Drive API转幻灯片为PDF时生成空文件问题

解决浏览器端用gapi调用Google Drive API导出幻灯片为PDF并上传后文件为空的问题

你的问题出在gapi.client.drive.files.export返回的响应处理方式错误——gapi.client默认会将响应解析为JSON格式,但PDF是二进制数据,直接取response.body得到的不是有效的二进制内容,导致生成的Blob为空,最终上传的文件没有数据。

以下是修正后的完整实现方案:

核心思路

  1. 放弃使用gapi.client.drive.files.export,改用原生fetch调用Drive API的导出端点,直接获取二进制Blob数据
  2. 同样用fetch调用Drive API的文件创建端点,以multipart/form-data格式上传Blob,确保数据正确传输

修正后的代码

async function createPdfFile() {
  // 确保gapi已加载并获取到授权令牌
  const accessToken = gapi.auth.getToken().access_token;
  if (!accessToken) {
    console.error("未获取到授权令牌");
    return;
  }

  const mimeType = "application/pdf";
  const fileName = "Trial upload.pdf";

  try {
    // 1. 导出Google幻灯片为PDF Blob
    const exportResponse = await fetch(
      `https://www.googleapis.com/drive/v3/files/${fileId}/export?mimeType=${encodeURIComponent(mimeType)}`,
      {
        headers: {
          Authorization: `Bearer ${accessToken}`
        }
      }
    );

    if (!exportResponse.ok) {
      throw new Error(`导出失败: ${exportResponse.statusText}`);
    }
    const pdfBlob = await exportResponse.blob();

    // 2. 构建multipart/form-data请求体,包含元数据和文件内容
    const formData = new FormData();
    // 添加文件元数据(JSON字符串)
    formData.append(
      "metadata",
      new Blob(
        [
          JSON.stringify({
            name: fileName,
            parents: [folderId],
            mimeType: mimeType,
            supportsAllDrives: true
          })
        ],
        { type: "application/json" }
      )
    );
    // 添加PDF文件内容
    formData.append("file", pdfBlob);

    // 3. 上传PDF到指定Drive文件夹
    const uploadResponse = await fetch(
      "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&supportsAllDrives=true",
      {
        method: "POST",
        headers: {
          Authorization: `Bearer ${accessToken}`
        },
        body: formData
      }
    );

    if (!uploadResponse.ok) {
      throw new Error(`上传失败: ${uploadResponse.statusText}`);
    }
    const result = await uploadResponse.json();
    console.log("PDF文件创建成功,ID:", result.id);
    return result.id;
  } catch (error) {
    console.error("处理失败:", error);
  }
}

// 调用函数
createPdfFile();

关键说明

  • 为什么不用gapi.client处理导出和上传?
    gapi.client设计用于处理JSON格式的API响应和请求,对于二进制数据的传输支持有限。直接用fetch可以更灵活地处理二进制Blob,以及构建multipart/form-data格式的上传请求,这是Drive API接收文件上传的标准方式。
  • 权限要求
    确保已申请以下OAuth2权限:
    • https://www.googleapis.com/auth/drive.readonly(用于导出幻灯片)
    • https://www.googleapis.com/auth/drive.file 或 https://www.googleapis.com/auth/drive(用于上传文件到指定文件夹)

内容的提问来源于stack exchange,提问作者John Neves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 06:05:26