我知道有关如何检查文件是否存在的问答by name (using hasnext()
)。不过我需要检查一下按文件 ID,最好没有高级 Drive API。
披露:我写了一个基于错误处理的解决方案:
function ifFileExists(id){
try {DriveApp.getFileById(id);return true;}
catch(e) {return false}
}
但这感觉很笨拙。有人知道更好的解决方案吗?
我相信您的目标如下。
- 您想要使用 Google Apps 脚本检查文件 ID 是否存在。
- 你不想使用
DriveApp.getFileById(id)
和驱动 API。
在这种情况下,作为解决方法,如何使用缩略图链接进行检查?Ref https://stackoverflow.com/q/25648388在这种情况下,当文件 ID 存在时,状态代码为200
被返回。另一方面,当文件ID不存在时,会出现类似的错误Error 404 (Not Found)
发生。我认为这种情况可能可以用于您的情况。当这反映在示例脚本中时,下面的示例脚本怎么样?在此示例脚本中,UrlFetchApp
用来。
示例脚本:
function myFunction() {
const fileId = "###"; // Please set the file ID.
const res = UrlFetchApp.fetch(`https://drive.google.com/thumbnail?id=${fileId}`, { muteHttpExceptions: true }).getResponseCode() == 200 ? true : false;
console.log(res);
}
-
在这种情况下,当res
is true
and false
,分别表示文件ID存在和不存在。
-
在这种情况下,不需要启用 Drive API,只需启用以下范围:https://www.googleapis.com/auth/script.external_request
用来。
-
当你的脚本修改后,下面修改后的脚本怎么样?
function ifFileExists(id){
return UrlFetchApp.fetch(`https://drive.google.com/thumbnail?id=${id}`, { muteHttpExceptions: true }).getResponseCode() == 200 ? true : false;
}
参考:
- 获取(网址,参数) https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetchurl,-params
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)