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

使用Google Apps Script调用云端硬盘图片返回Status code 403问题

解决Google Apps Script中Drive图片403访问问题

问题描述

开发图片画廊时,通过Google Apps Script读取Google表格中的图片ID动态展示图片,此前功能正常,现在返回403状态码。编写极简测试脚本(硬编码单张图片)后,同样触发403错误,但直接访问图片链接可正常显示。

测试代码

Code.gs:

function doGet(request) {
  var htmlTemplate=HtmlService.createTemplateFromFile("prova");
  return htmlTemplate.evaluate();
}

prova.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <title></title>
</head>
<body>
   xxxxxxxxxxxxxxxxxxxxxx
   <img src="https://drive.google.com/uc?export=view&id=11CakSm75WDYnpfd_Qs2LlYoVmJwdAmUR" alt="sample" />
  </div>
</body>
</html>

错误响应头

Stato:              403
Versione:           HTTP/2
Trasferito:         1,39 kB (dim. 0 B)
Referrer Policy:    strict-origin-when-cross-origin
Priorità richiesta: Low
Risoluzione DNS:    Sistema

问题原因

Google Drive的uc?export=view链接带有防盗链机制,当请求来自Google Apps Script部署的域名(script.google.com)时,请求会携带该域名作为Referrer,触发Drive的访问限制,返回403错误。

解决方案

方案1:添加referrerpolicy属性(推荐)

直接在<img>标签中添加referrerpolicy="no-referrer",让请求不携带Referrer信息,避开防盗链检查:

<img src="https://drive.google.com/uc?export=view&id=11CakSm75WDYnpfd_Qs2LlYoVmJwdAmUR" alt="sample" referrerpolicy="no-referrer" />

方案2:确认图片共享权限

确保目标图片的共享权限设置为**“知道链接的任何人都可查看”**:

  • 打开Drive中的图片文件,点击右上角“共享”按钮
  • 选择“知道链接的任何人”,权限级别设为“查看者”
  • 保存设置(若图片在文件夹中,需同时确认文件夹权限或单独设置文件权限)

方案3:通过Apps Script Drive服务返回图片(适合少量图片)

利用Google Apps Script的Drive API获取图片Blob,转换为Data URL展示:

  1. 修改Code.gs,添加获取图片Blob的函数:
function doGet(request) {
  var htmlTemplate=HtmlService.createTemplateFromFile("prova");
  return htmlTemplate.evaluate();
}

function getImageBlob(imageId) {
  var file = DriveApp.getFileById(imageId);
  return file.getBlob();
}
  1. 修改prova.html,通过google.script.run获取并展示图片:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <title></title>
</head>
<body>
   xxxxxxxxxxxxxxxxxxxxxx
   <img id="sample-img" alt="sample" />
   <script>
     google.script.run.withSuccessHandler(function(blob) {
       const imgSrc = `data:${blob.getContentType()};base64,${Utilities.base64Encode(blob.getBytes())}`;
       document.getElementById('sample-img').src = imgSrc;
     }).getImageBlob('11CakSm75WDYnpfd_Qs2LlYoVmJwdAmUR');
   </script>
</body>
</html>

注意:部署脚本时需将权限设置为“任何人,甚至匿名”,并确保脚本已授权Drive API访问权限。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 05:05:11