首页 > 解决方案 > Google drive api:如何从我的脚本中获取绝对链接(最终)作为返回

问题描述

我需要绝对的 google drive api 链接作为我的脚本的结果,但我不知道如何。

这是我的脚本:

我有一个 html 表单,我将媒体文件上传到谷歌驱动器并返回文件。这是我的代码:

<form id="form">
  <input name="file" id="uploadfile" type="file">
  <input name="filename" id="filename" type="text">
  <input id="submit" type="submit">
</form>
<script>
const form = document.getElementById('form');
form.addEventListener('submit', e => {
  e.preventDefault();
  const file = form.file.files[0];
  const fr = new FileReader();
  fr.readAsArrayBuffer(file);
  fr.onload = f => {
    
    const url = "https://script.google.com/macros/s/###/exec";  // <--- Please set the URL of Web Apps.
    
    const qs = new URLSearchParams({filename: form.filename.value || file.name, mimeType: file.type});
    fetch(`${url}?${qs}`, {method: "POST", body: JSON.stringify([...new Int8Array(f.target.result)])})
    .then(res => res.json())
    .then(e => console.log("https://drive.google.com/uc?export=download&id=" + e.fileId))
    .catch(err => console.log(err));
  }
});
</script>

这是我的服务器脚本

function doPost(e) {
  const folderId = "root";  // Folder ID which is used for putting the file, if you need.

  const blob = Utilities.newBlob(JSON.parse(e.postData.contents), e.parameter.mimeType, e.parameter.filename);
  const file = DriveApp.getFolderById(folderId || "root").createFile(blob);
  const responseObj = {filename: file.getName(), fileId: file.getId(), fileUrl: file.getUrl()};
  return ContentService.createTextOutput(JSON.stringify(responseObj)).setMimeType(ContentService.MimeType.JSON);
}

一位 stackoverflow 用户描述了如何获取我需要的链接。如何将此步骤放入脚本中?

  1. 从共享链接https://drive.google.com/file/d/your_file_id/view?usp=sharing获取文件 ID

  2. 构建直接链接http://docs.google.com/uc?export=open&id=your_file_id

  3. 将直接链接粘贴到网络浏览器中,然后按 Enter

  4. 浏览器重定向后复制生成的 URL 注意:这将是一个更长的 URL,如下所示:https ://doc-XX-XX-docs.googleusercontent.com/docs/securesc/XXXXXXXXXXXXXXXXXXXXX/XXXXXXXXXXXXXXXXXXXX /000000000000000/0000000000000000000000/*/your_file_id?e=open

使用这个最终 URL 是我可以让上传的声音文件与 Actions on Google 一起使用的唯一方法。

标签: javascripturlgoogle-apps-scriptgoogle-drive-apiactions-on-google

解决方案


获取fileUrl后,用于Urlfetch获取资源。如果它被重定向,您将在标头中获得带有重定向 url 的状态代码 。如果需要,可以使用 处理授权。302LocationScriptApp.getOAuthToken()

const url = `https://docs.google.com/uc?export=open&id=${file.getId()}`;
const response = UrlFetchApp.fetch(url,{
  headers: {
    Authorization: `Bearer ${ScriptApp.getOAuthToken()}`
  },
  followRedirects: false
});
const statusCode = response.getStatusCode();
if (String(statusCode)[0] === "3") console.log(response.getAllHeaders()['Location'])
else console.log("No redirect")

推荐阅读