【发布时间】:2018-08-15 20:14:38
【问题描述】:
https://docs.google.com/spreadsheets/d/1sQyBTh7xCptnvr2SOQyEovmgIi6U-UapvDQOphk2Qxg/edit?usp=sharing
上面是我的 Google 表格文件,该文件链接到一个表单,该表单上传收据图像文件并为上传的收据分类信息。
我对应用脚本工作有两个要求:
1) Get a short URL for the uploaded file.
STATUS: ACHIEVED!!!
2) Fetch the name of the uploaded file for reference.
STATUS: NOT ACHIEVED, GET ERROR CODE BELOW WHEN CLICKING MENU ITEM
TO RUN THE SCRIPT.
错误:“找不到具有给定 ID 的项目,或者您无权访问它。”
稍后我将粘贴我的应用脚本代码。
这是我迄今为止所做的:
1) Enabled both the Drive API & URL Shortener APIs in the script
2) Enabled both APIs on Google API Console for this project
3) Saved my code in Apps Script
4) Ran onOpen() function to establish the Custom Menu in my spreadsheet
(it adds the menu when I refresh the spreadsheet).
5) I am the owner of all of the following:
+the Drive account ALL of the pertinent files are stored on,
+the App Script that was created,
+the project in the Google API console.
6) I have given consent to access the process when the Script first runs
with the same Google Account.
代码如下:
function onOpen() {
SpreadsheetApp.getUi()
.createMenu("URL Manager")
.addItem("Shorten","short")
.addItem("Get File Names","names")
.addToUi();
}
function short() {
var range = SpreadsheetApp.getActiveRange(), data = range.getValues();
var output1 = [];
for(var i = 0, iLen = data.length; i < iLen; i++) {
var url = UrlShortener.Url.insert({longUrl: data[i][0]});
output1.push([url.id]);
}
//puts the short url one column to the right
range.offset(0,1).setValues(output1);
}
function names() {
var range = SpreadsheetApp.getActiveRange(), data = range.getValues();
//var data must be converted to string since it is the long url of the
//file, then parsed for index of "=" (var n), then I sliced out the fileID
//with var m
var str = data.toString();
var n = str.indexOf("=");
var m = str.slice(n+1)
var output2 = [];
for(var i = 0, iLen = data.length; i < iLen; i++) {
var file = DriveApp.getFileById({fileID: m[i][0]});
output2.push([file.getName()]);
}
//puts the file name 1 column to the left
range.offset(0,-1).setValues(output2);
}
所以我重新加载了我的电子表格,单击以激活我想要为其获取短 url 和文件名的单元格,然后单击菜单项以执行脚本功能。 short() 有效, names() 无效。请参阅上面的错误。
这是我的问题:
我可以做些什么来消除文件访问的隐藏限制?
我找到了这段代码的前 2/3(onOpen 和短函数)以及一个很好的解释 here。谢谢,亚历克斯!
【问题讨论】:
标签: google-apps-script google-sheets google-drive-api google-url-shortener