javascript - 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 用户描述了如何获取我需要的链接。如何将此步骤放入脚本中?
从共享链接https://drive.google.com/file/d/your_file_id/view?usp=sharing获取文件 ID
将直接链接粘贴到网络浏览器中,然后按 Enter
浏览器重定向后复制生成的 URL 注意:这将是一个更长的 URL,如下所示:https ://doc-XX-XX-docs.googleusercontent.com/docs/securesc/XXXXXXXXXXXXXXXXXXXXX/XXXXXXXXXXXXXXXXXXXX /000000000000000/0000000000000000000000/*/your_file_id?e=open
使用这个最终 URL 是我可以让上传的声音文件与 Actions on Google 一起使用的唯一方法。
解决方案
获取fileUrl后,用于Urlfetch
获取资源。如果它被重定向,您将在标头中获得带有重定向 url 的状态代码 。如果需要,可以使用 处理授权。302
Location
ScriptApp.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")
推荐阅读
- javascript - 使用 react-native-webview 的 stopLoading 后 Webview 冻结
- javascript - 图像未在 Vue-bootstrap 中显示
- html - 屏幕渲染时如何聚焦输入
- java - 在 Java 中使用 JEST API 为索引添加别名和删除索引
- php - ErrorException: ZipArchive::close(): 创建临时文件失败: 没有错误
- python - Efficiently produce 64 by 10 matrix from 64 and 10 long vectors in python
- c++ - 为什么 g++ 静态链接不适用于 Windows 中的 sfml?
- r - 根据时间计算事件差异
- android - React Native,未连接任何应用程序。向所有 React Native 应用程序发送“重新加载”失败
- java - 如果@SpringBootTest 无法加载 ApplicationContext,如何使故障安全插件失败