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

使用Google Drive API无法获取PDF、Doc等类型文件内容的问题问询

Google Drive API获取非文本类文件内容解决方法

问题原因

  • alt=media参数仅支持读取非Google Workspace格式的二进制文件内容,Google原生文档(Google Doc、Google Sheet、Google Slide等)调用该参数只会返回元数据;若你上传的PDF、Doc类非原生文件也仅返回元数据,通常是请求配置错误或权限不足导致。

解决方法

1. 非Google原生文件(用户上传的PDF、Docx、Xlsx等)

调整axios请求配置,新增responseType指定接收二进制流,同时移除多余的developerKey参数(请求头已携带Bearer token,重复传密钥可能触发权限冲突):

axios.get(`https://www.googleapis.com/drive/v2/files/${data.docs[0].id}?alt=media`, {
  headers: {
    Authorization: `Bearer ${this.state.token}`
  },
  // 声明响应类型为blob,避免axios默认将二进制流转为JSON格式
  responseType: 'blob'
}).then(res => {
  // res.data即为文件二进制内容,可直接用于下载或预览
  const blobUrl = window.URL.createObjectURL(new Blob([res.data]));
  const downloadLink = document.createElement('a');
  downloadLink.href = blobUrl;
  downloadLink.download = '自定义文件名';
  downloadLink.click();
})

2. Google原生Workspace文档

这类文件需调用专门的导出接口,指定需要导出的目标格式MIME类型即可获取内容:

// 导出为PDF填application/pdf,导出为Word文档填application/vnd.openxmlformats-officedocument.wordprocessingml.document
const targetMimeType = 'application/pdf';
axios.get(`https://www.googleapis.com/drive/v2/files/${data.docs[0].id}/export`, {
  headers: {
    Authorization: `Bearer ${this.state.token}`
  },
  params: {
    mimeType: targetMimeType
  },
  responseType: 'blob'
})

3. 权限校验

确认OAuth2授权时申请的权限范围至少包含https://www.googleapis.com/auth/drive.readonly,权限不足也会导致仅能获取元数据无法读取文件内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 19:09:03