How to Share Files in Google Drive with Multiple Users | TechTalkBot
The Google Drive API makes it easy to programmatically share files and folders with other users using Apps Script.
For example, here is a code snippet that you can use to share the file with another Google account user and give them edit access to the file. Replace the role from writer to reader to give them read-only access.
const shareFilesInGoogleDrive = (fileOrFolderId, emailAddress) => {
Drive.Permissions.insert(
{
role: "writer", // or "reader" or "commenter"
value: emailAddress,
type: "user",
},
fileOrFolderId,
{
supportsAllDrives: true,
sendNotificationEmails: true,
}
);
};
We recommend setting the sendNotifications flag to true because an email notification will be sent when the file is shared with a user who may not have a Google account.
How to Share Files in Google Drive with Multiple Users | TechTalkBot
One limitation of the Drive API is that you can only share files with one user at a time. Google Apps Script is synchronous, it does not support JavaScript Promises asynchronous / waiting pattern, so it cannot run code in parallel.
There’s however a simple workaround to help you share a file or folder in Google Drive with multiple users in one go in parallel using the UrlFetchApp service.
const shareGoogleDriveFileWithMultipleUsers = () => {
const fileId = "<Drive File Id>";
const editors = ["angus@gmail.com", "kiran@school.edu", "jacob@corp.com"];
const API = "https://www.googleapis.com/drive/v3/files";
const queryString = "supportsAllDrives=true&sendNotifications=true";
const accessToken = ScriptApp.getOAuthToken();
const requests = editors.map((emailAddress) => ({
url: `${API}/${fileId}/permissions?${queryString}`,
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
muteHttpExceptions: true,
payload: JSON.stringify({
role: "writer",
type: "user",
emailAddress: emailAddress,
}),
}));
UrlFetchApp.fetchAll(requests);
};
In the snippet above, we are directly invoking the Google Drive API (v3) instead of the DriveApp service of App Script. The fetchAll
allows you make multiple HTTP requests in a single request and returns an array of responses.
Please ensure that the following scopes are added in your appsscript.json
file:
{
...
"oauthScopes": [
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/drive",
],
...
}