问题描述
Google Drive API v3最近更改,因此文件只能存在于一个文件夹中。这破坏了我用来将文件夹加载到每个域用户的“我的云端硬盘”(带有ID为“ root”的文件夹)中的Apps脚本工具。
var service = getService(userEmail);
var url = 'https://www.googleapis.com/drive/v3/files/' + driveId +'?addParents=' + parentId;
Logger.log(url);
var options = {
'contentType': 'application/json','method' : 'patch','headers' : { Authorization: 'Bearer ' + service.getAccesstoken() },//https://github.com/googleworkspace/apps-script-oauth2
'muteHttpExceptions': true
};
var response = UrlFetchApp.fetch(url,options);
var found = response.getResponseCode()
if (found == 200) { found = 'Added to My Drive' } else {
Logger.log('Failed with response code: %s',found);
}
解决方法
使用Google云端硬盘的新快捷方式MIME类型!您可以参考Google的示例Create a shortcut to a Drive file获取提示。请记住,高级驱动器服务仅限于Drive API v2,但URLFetchApp也可以使用Drive API v3。
以下代码用于URLFetchApp。如果您想使用高级驱动器服务,请改用以下答案:How to create a shortcut in Google Drive Apps Script instead of multiple parents
/*
* Create a new shortcut using UrlFetchApp.
*
* @param {String} driveId Id of the file/folder to use as a shortcut target.
* @param {String} userEmail User email address for change context and OAuth token.
* @param {String} parentId The parent folder for the shortcut file.
* @param {String} driveName The display name of the shortcut.
* https://developers.google.com/drive/api/v3/shortcuts
* https://developers.google.com/drive/api/v3/reference/files/create
* https://github.com/googleworkspace/apps-script-oauth2
*/
function TEST_addShortcut() { addShortcut('DriveKey0123456789ABCDEabcde','Username@CompanyDomain.com','root','The file or folder name')
};
function addShortcut(driveId,userEmail,parentId,driveName) {
var service = getService(userEmail); //apps-script-oauth2 library
if (service.hasAccess()) {
Logger.log("addShortcut hasAccess,User %s",userEmail);
var url = 'https://www.googleapis.com/drive/v3/files/';
var data = {
'shortcutDetails': {'targetId': driveId},'name' : driveName,'mimeType' : 'application/vnd.google-apps.shortcut','parents' : parentId //Use Id 'root' for user's My Drive folder
};
var options = {
'method' : 'POST','contentType': 'application/json','headers' : { Authorization: 'Bearer ' + service.getAccessToken() },'payload' : JSON.stringify(data) // Convert JavaScript object to JSON string
};
var response = UrlFetchApp.fetch(url,options);
var resultStringy = JSON.stringify(response,null,2);
var respCode = response.getResponseCode()
Logger.log('addShortcut code %s,result: %s',respCode,resultStringy);
return (respCode == 200);
} else {
Logger.log('addShortcut getLastError: %s',service.getLastError());
Logger.log('addShortcut(%s) = %s','No Access');
return null; //Service does not have access
}
};