如何通过自定义函数/脚本通过正确的授权从Google表格中获取文件名中的文件URL [英] How to get the file URL from file name in Google Sheets with correct Authorization via custom function/script
问题描述
我想创建一个自定义函数,从Google表格中的文件名中提取云端硬盘网址。
I would like to create a custom function that pulls a Drive URL from a file name in Google Sheets.
因此,请使用以下代码:
So, using the code below:
- 如果我在单元格中有有效的文件名
A1
-
函数
= getFile(A1)
将返回URL
- 当我从脚本编辑器中运行脚本时,返回值有效。
- 当我运行函数
getFile()
时在我的工作表中,我收到以下错误。
- When I run my script from within the script editor, the return value works.
- When I run the function
getFile()
from within my sheet, I get the error below.
我的代码:
function getFile(cell) {
var filename = encodeURI(cell);
var url = "https://www.googleapis.com/drive/v3/files?fields=files(id,name)&q=name+contains+'" + filename + "' and trashed=false";
var params = {
method: "GET",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var res = UrlFetchApp.fetch(url, params).getContentText();
var json = JSON.parse(res);
return res; // outputs response below
if(json){
var objFiles = json.files[0];
var fileID = objFiles.id
var resURL = "https://docs.google.com/spreadsheets/d/" + fileID;
Logger.log(resURL);
//return resURL; // only works when run within script editor
}
}
错误:
"{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
"
我猜我的Auth令牌有问题。有人可以指示我解决这个问题吗?提前致谢!
I'm guessing something's wrong with my Auth token. Can someone direct me to resolving this? Thanks in advance!
推荐答案
@我' - '我的答案是正确的。虽然我不确定这是否是您想要的,但这个解决方法怎么样?我也经历过同样的问题。那时,我使用了以下解决方法。
@I'-'I's answer is correct. Although I'm not sure whether this is what you want, how about this workaround? I have also experienced the same issue. At that time, I had used the following workaround.
- 使用PropertiesService设置并获取访问令牌。
流程如下。
- 由时间驱动的触发器每1小时设置一次访问令牌。
- 这样,访问令牌每1小时更新一次。因为访问令牌的到期时间是1小时。
- 这样,可以使用访问令牌。
修改后的脚本:
请将此功能安装为时间驱动的触发器。当然,你可以手动运行这个函数。
Modified script:
Please install this function as the time-driven trigger. Of course, you can run manually this function.
function setAccessToken() {
PropertiesService.getScriptProperties().setProperty("accessToken", ScriptApp.getOAuthToken());
}
在您的脚本中,请修改如下。
In your script, please modify as follows.
var params = {
method: "GET",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
To:
To:
var params = {
method: "GET",
headers: {"Authorization": "Bearer " + PropertiesService.getScriptProperties().getProperty("accessToken")},
muteHttpExceptions: true
};
注意:
- 在这种情况下,访问令牌的所有者是项目的所有者。
- 我认为这也可以由CacheService使用。
- PropertiesService
这篇关于如何通过自定义函数/脚本通过正确的授权从Google表格中获取文件名中的文件URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!