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

如何将Google Drive中TXT文件文本内容插入Google站点?

解决Google站点嵌入Google Drive TXT文件内容的问题

原代码失效原因

你用本地路径G:/My Drive/path/to/test_file/test.txt调用fetch完全不可行:

  • 浏览器安全机制禁止直接访问本地文件系统路径
  • Google Drive文件必须通过云端可访问的URL获取,而非本地挂载路径

方案一:公开文件后用可访问URL获取(快速简单)

若允许将TXT文件设为公开访问,这是最省事的方法:

  1. 打开Google Drive中的目标TXT文件,点击右上角「分享」,设置权限为「知道链接的任何人都可以查看」
  2. 复制共享链接(格式如https://drive.google.com/file/d/[FILE_ID]/view?usp=sharing)
  3. 将链接转换为直接下载格式:https://drive.google.com/uc?export=download&id=[FILE_ID],替换[FILE_ID]为共享链接中/d/与/view之间的字符串
  4. 修改HTML代码如下,嵌入Google站点的「嵌入代码」块:
<html>
<body>
<div id="text-container"></div>

<script>
  // 替换为你的转换后URL
  fetch("https://drive.google.com/uc?export=download&id=你的文件ID")
    .then(response => {
      if (!response.ok) throw new Error("文件加载失败");
      return response.text();
    })
    .then(text => {
      document.getElementById('text-container').textContent = text; // 用textContent避免HTML注入风险
    })
    .catch(err => {
      document.getElementById('text-container').textContent = `加载错误:${err.message}`;
    });
</script>
</body>
</html>

方案二:不公开文件,用Google Apps Script读取(更安全)

若不想公开文件,可借助Google Apps Script读取同文件夹内的TXT文件,再通过Web应用提供内容:

步骤1:创建并部署Apps Script

  1. 打开Google Apps Script(通过Google工作台或直接搜索进入),新建空白项目
  2. 替换默认代码为以下内容(修改test.txt为你的实际文件名):
function doGet() {
  // 获取脚本所在文件夹(与站点、TXT文件同目录)
  const folder = DriveApp.getFileById(ScriptApp.getScriptId()).getParents().next();
  // 查找目标TXT文件
  const txtFiles = folder.getFilesByName("test.txt");
  if (!txtFiles.hasNext()) {
    return ContentService.createTextOutput("未找到目标文件").setMimeType(ContentService.MimeType.TEXT);
  }
  // 读取并返回文件内容,允许跨域访问
  const content = txtFiles.next().getBlob().getDataAsString();
  return ContentService.createTextOutput(content)
    .setMimeType(ContentService.MimeType.TEXT)
    .setHeaders({ "Access-Control-Allow-Origin": "*" });
}
  1. 点击「部署」>「新部署」,选择「Web应用」类型:
    • 执行:选择「我」
    • 访问权限:按需选择,比如「任何人,甚至匿名」(无需身份验证)
    • 部署后复制生成的Web应用URL

步骤2:在Google站点中调用Web应用

将以下代码嵌入站点的「嵌入代码」块,替换为你的Web应用URL:

<html>
<body>
<div id="text-container"></div>

<script>
  fetch("你的Web应用URL")
    .then(response => {
      if (!response.ok) throw new Error("内容加载失败");
      return response.text();
    })
    .then(text => {
      document.getElementById('text-container').textContent = text;
    })
    .catch(err => {
      document.getElementById('text-container').textContent = `加载错误:${err.message}`;
    });
</script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:20:07