【问题标题】:Unwanted "content-type: text/plain;charset=UTF-8" header in Google Drive API ResponseGoogle Drive API 响应中不需要的“content-type: text/plain;charset=UTF-8”标头
【发布时间】:2026-01-22 11:45:01
【问题描述】:

我正在使用浏览器 GAPI 库从 Google Drive 请求一段二进制数据。来自 google 服务器的响应总是带有 content-type: text/plain;charset=UTF-8 标头,因此,浏览器总是将二进制数据解码为 UTF-8 字符串。

更重要的是,解码过程似乎为原始二进制数据添加了填充。例如,一个 282 字节的二进制文件经过 UTF-8 解码后变成了 422 字节长。

有没有办法告诉 Google API 服务器更改内容类型标头?

或者有没有办法绕过响应体的预处理而获取原始响应?

这里列出了我的请求代码:

currentApiRequest = {
    path: `https://www.googleapis.com/drive/v3/files/${fileID}`,
    params: {
        alt: "media"
    }
}
gapi.client.request(currentApiRequest).then(
    (response) => {
                let data = response.body;
                console.log(byteSize(data));
                console.log(data);
    }
)

【问题讨论】:

  • 如果它的二进制数据为什么不直接使用 webContentLink 呢?
  • 因为 cors,我根本无法获取 webContentLink...

标签: javascript google-drive-api client-side google-api-js-client


【解决方案1】:

下面的修改怎么样?在这个修改中,首先将检索到的数据转换为Unit8Array并转换为blob。

修改脚本:

const fileID = "###"; // Please set your file ID.
currentApiRequest = {
  path: `https://www.googleapis.com/drive/v3/files/${fileID}`,
  params: {alt: "media"}
};
gapi.client.request(currentApiRequest)
.then((response) => {
  let data = response.body;
  const blob = new Blob([new Uint8Array(data.length).map((_, i) => data.charCodeAt(i))]);

  // When you use the following script, you can confirm whether this blob can be used as the correct data.
  const filename = "sample.png"; // Please set the sample filename.
  const a = document.createElement('a');
  document.body.appendChild(a);
  a.href = URL.createObjectURL(blob);
  a.download = filename;
  a.click();
});

参考资料:

【讨论】: