creating folders in shared drives - Using Apps Script with Advanced Drive v3

661 views
Skip to first unread message

TempleSnr

unread,
Apr 13, 2024, 7:22:20 AM4/13/24
to Google Apps Script Community
hi, I'm trying to create folder using the Advanced Drive functionality in Apps Script.
function createFolderDriveApi(parentId, folderName) {
const fileMetadata = {
name: folderName,
mimeType: 'application/vnd.google-apps.folder',
parents: [parentId] // This should be the ID of the parent folder or shared drive.
};

try {
const folder = Drive.Files.create(fileMetadata, { supportsAllDrives: true });
return folder;
} catch (error) {
Logger.log(`Error creating folder '${folderName}' in parent ID '${parentId}': ${error}`);
throw error; // Rethrow the error for further handling if necessary
}
}

I get an error
12:15:06 PM
Info
Error creating folder 'Foldername1' in parent ID '0A---PVA': Exception: The mediaData parameter only supports Blob types for upload.
12:15:06 PM
Info
Error creating folders for Foldername1: Exception: The mediaData parameter only supports Blob types for upload.
The parentId is a valid shared drive ID. 
Foldername1 is just a string.

It looks as though it's trying to upload a file but I'm not sure why.
I'm guessing there's a mistake - can anyone see it?

DimuDesigns

unread,
Apr 13, 2024, 10:22:36 AM4/13/24
to Google Apps Script Community
According to the GAS GUI's auto-complete pop-up documentation, there are three variants of the Drive.Files.create method:

Drive.Files.create(resource);
Drive.Files.create(resource, mediaData);
Drive.Files.create(resource, mediaData, optionalArgs)

The method expects the 2nd argument to be a Blob and the 3rd argument to be the optional arguments object. Since you're not uploading a file you can try setting the 2nd argument to null or undefined.

Fabrice Faucheux

unread,
Apr 13, 2024, 10:58:11 AM4/13/24
to Google Apps Script Community
Hi,

It looks like the issue you are encountering in your Google Apps Script when trying to create a folder using the Advanced Drive API is related to how the `Drive.Files.create` method is called. Specifically, the error message suggests that the API is expecting a Blob type for file uploads, which is not what you are intending as you're trying to create a folder.

This confusion typically arises because the `Drive.Files.create` method in Apps Script can be used both for creating files and folders, depending on the `mimeType`. When creating files, it often requires a second parameter for `mediaData` (the file's content), which should be a Blob if provided. Since you're trying to create a folder and not upload a file, no `mediaData` is needed, but it seems like your script setup may be triggering an expectation for this parameter.

To address this issue, you need to ensure that you are correctly using the `Drive.Files.create` function for creating folders. Here's a refined version of your function:


function createFolderDriveApi(parentId, folderName) {
    const fileMetadata = {
        name: folderName,
        mimeType: 'application/vnd.google-apps.folder',
        parents: [parentId]  // This should be the ID of the parent folder or shared drive.
    };

    const optionalArgs = {
        supportsAllDrives: true
    };

    try {
        // Explicitly set mediaData as null
        const folder = Drive.Files.create(fileMetadata, null, optionalArgs);

        return folder;
    } catch (error) {
        Logger.log(`Error creating folder '${folderName}' in parent ID '${parentId}': ${error}`);
        throw error;  // Rethrow the error for further handling if necessary
    }
}

Make sure that:
1. You have enabled the Advanced Drive API service in your Google Apps Script project.
2. You have the correct permissions to create folders in the specified parent ID.

The adjusted part here is the clearer separation of params from fileMetadata and ensuring that no additional, unintended data is sent to the `Drive.Files.create` method which could be interpreted as `mediaData`.

If you continue to face issues, double-check the permissions on the parent folder or shared drive, and ensure that the Drive API is enabled and properly configured in your Google Cloud Project associated with the Apps Script.

Fabrice

Temple Rodgers

unread,
Apr 13, 2024, 4:01:21 PM4/13/24
to google-apps-sc...@googlegroups.com
Thank you very much Fabrice and DimuDesigns. Fabrice, I'll try this tomorrow.
Temple

--
You received this message because you are subscribed to a topic in the Google Groups "Google Apps Script Community" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/google-apps-script-community/VpvWOjTjI7k/unsubscribe.
To unsubscribe from this group and all its topics, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-apps-script-community/74ad2b16-6db2-437e-bab9-ee55a6cb5e2dn%40googlegroups.com.

Disclaimers apply, for full details see: https://hackney.gov.uk/email-disclaimer

TempleSnr

unread,
Apr 13, 2024, 5:17:06 PM4/13/24
to Google Apps Script Community
Absolutely brilliant! Worked first time, thank you @Fabrice.

Guadalupe Rosiles

unread,
Apr 15, 2024, 3:19:12 AM4/15/24
to google-apps-sc...@googlegroups.com
Disclaimers apply, for full details see: https://hackney.gov.uk/email-disclaimer

--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-apps-script-community/eccb778f-7fd7-4bd1-9edc-59e523e3377dn%40googlegroups.com.

TempleSnr

unread,
Apr 17, 2024, 3:20:41 AM4/17/24
to Google Apps Script Community
Well, I'm just going to have a moan, it's very frustrating, please comment if you can offer any helpful hints.
Using the Drive v3 API is a real disappointment. Firstly, it's incredibly slow. I need to create 50,000 folders ... at first, I managed to create 1500 comfortably before the script would time out and make sure that my spreadsheet was updated. Then, when I tried to run the script every 30 minutes (I would have preferred 40, but it seems that's not possible, I don't know why) I found that sometimes it wouldn't complete so I dropped it to creating 1000 folders in the 30 minute slot. Now I've found that isn't enough time. Not only that but for no apparent reason the create folder will fail  e.g.:
Error
GoogleJsonResponseException: API call to drive.files.create failed with error: The operation was successful, but there was an error preparing the response. at createFolderInSharedDrive(createSharedDriveFolders:125:38) at createNewUsersFolders(createSharedDriveFolders:91:25)


Out of 22 runs, I've had 3 timed out and two failures. The annoyance is that I store the foldernames and id's then write them to a sheet at the end of the run, so if it times out or fails then I've created a load of folders and haven't stored the details. Very annoying
Here's my code
:
function createFolderInSharedDrive(googleEmail, googleID, surnameLetter, ID, sharedDriveId) {
try {
const parentFolder = Drive.Files.create({
'name': `${googleID} [${ID}]`,
'mimeType': 'application/vnd.google-apps.folder',
'parents': [sharedDriveId]
}, null, {supportsAllDrives: true});

const subfolderNames = ['Absence',
'Form',
'Appraisal',
'Pre-employment',
'Contractual',
'Employee',
'Payments',
'Management',
'Termination',
'Confidential'];

const subfolders = [];
subfolderNames.forEach(name => {
try {
const folder = Drive.Files.create({
'name': `${name} - ${googleID} [${ID}]`,
'mimeType': 'application/vnd.google-apps.folder',
'parents': [parentFolder.id]
}, null, {supportsAllDrives: true});
subfolders.push(folder); // Only add the folder if creation was successful
} catch (error) {
Logger.log(`Error creating subfolder '${name}': ${error}`);
}
});

// Log success message
if (subfolders.length > 0) {
Logger.log(
'Folders created successfully,' + parentFolder.getName() + ',' + parentFolder.getId() + ',' +
subfolders.map(folder => folder.getName() + ',' + folder.getId()).join('\n')
);
} else {
Logger.log('No subfolders were created successfully.');
}

// Construct folder details object
// and write output to the Folder_IDs sheet (in calling function)
const folderDetails = [
`'${ID}`,
googleEmail,
`${googleID} [${ID}]`,
surnameLetter,
sharedDriveId,
parentFolder.id,
...subfolders.flatMap(folder => folder ? [folder.name, folder.id] : [])
];
return folderDetails;
} catch (error) {
Logger.log('Error creating the main folder:', error);
throw error; // Re-throw to handle errors gracefully
}
}

Reply all
Reply to author
Forward
0 new messages