gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:01:32 26 4
gpt4 key购买 nike

我知道关于如何检查文件是否存在按名称(使用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在这种情况下,当文件 ID 存在时,状态代码为 200 的登录 HTML被退回。另一方面,当文件 ID 不存在时,会出现类似 Error 404 (Not Found) 的错误。发生。我认为这种情况可能可以用于您的情况。当这反射(reflect)在示例脚本中时,以下示例脚本如何?在此示例脚本中,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);
}
  • 在这种情况下,当 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;
    }

引用:

关于javascript - 如何检查 GAS 中文件是否存在(通过 id),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74247840/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com