Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

javascript - How to get the file URL from file name in Google Sheets with correct Authorization via custom function/script

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:

  1. If I have a valid file name in cell A1
  2. The function =getFile(A1) would return the URL

    • 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.

My code:

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:

"{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "authError",
    "message": "Invalid Credentials",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Invalid Credentials"
 }
}
"

I'm guessing something's wrong with my Auth token. Can someone direct me to resolving this? Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Custom functions runs as if run by a anonymous animal(user). ScriptApp.getOAuthToken will return a anonymous token without the required scopes. What you're attempting is not possible, unless the file in question is public.

References:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...