如何检查 GAS 中是否存在文件(通过 id)

Wil*_*emS 2 javascript null google-apps-script google-drive-api

我知道有关如何按名称检查文件是否存在的问答(使用hasnext())。但是,我需要通过文件 ID进行检查,最好不要使用高级 Drive API。

披露:我写了一个基于错误处理的解决方案:

function ifFileExists(id){
  try {DriveApp.getFileById(id);return true;}
  catch(e) {return false}
}
Run Code Online (Sandbox Code Playgroud)

但这感觉很笨拙。有人知道更好的解决方案吗?

Tan*_*ike 5

我相信您的目标如下。

  • 您想要使用 Google Apps 脚本检查文件 ID 是否存在。
  • 您不想使用DriveApp.getFileById(id)Drive API。

在这种情况下,作为解决方法,如何使用缩略图链接进行检查?Ref200在这种情况下,当文件 ID 存在时,返回状态代码为 的登录 HTML 。另一方面,当文件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);
}
Run Code Online (Sandbox Code Playgroud)
  • 此时,当restruefalse,分别表示该文件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;
      }
    
    Run Code Online (Sandbox Code Playgroud)

参考: