Google Apps脚本:将文件夹添加到文件夹

时间:2016-06-15 09:08:05

标签: google-apps-script google-drive-api

我使用脚本将带有图像的文件夹上传到(parent?)文件夹。当我这样做时,一次是以正确的方式创建文件夹结构。但是,当我第二次尝试时,它会在根目录中创建一个具有相同名称的新文件夹。

如何更改我的代码,以便有一个父文件夹,其中将添加图像文件夹?

目前:

  • 第一次:{​​{1}}(此文件夹中的图片)
  • 第二次新地图:/root/persons/test test@test.com/(此文件夹中的图片)

我想:
  /root/persons/test2 test2@test2.com/(此文件夹中的图片)

我的代码:

/root/persons/*(folders)/

2 个答案:

答案 0 :(得分:1)

这对我有用,可以在现有文件夹中创建文件夹

const parentFolder = DriveApp.getFolderById("1TukDeifX_nYZftbzODkUfD-hYlpx5TPg");
const folder1 = parentFolder.createFolder(Project + ", " + Date + ", " + Phone);

答案 1 :(得分:0)

您没有测试是否存在“Persons”文件夹,因此每次有新用户时都会重新创建该文件夹。我建议先在函数中执行此操作,如下所示:

/* Find the first level folder, create if the folder does not exist */
var firstLevelFolderName = "Persons";
var folders = DriveApp.getFoldersByName(firstLevelFolderName);
var firstLevelFolder = (folders.hasNext()) ? folders.next() : DriveApp.createFolder(firstLevelFolderName);

请注意使用ternary operator if..then..else将分配保留在一个语句中,而不是明确的?结构。对于“find vs create”评估的任何迭代器,可以使用相同的模式。

更新了脚本:

/* This function will process the submitted form */
function uploadFiles(form) {

  try {
    /* Find the first level folder, create if the folder does not exist */
    var firstLevelFolderName = "Persons";
    var folders = DriveApp.getFoldersByName(firstLevelFolderName);
    var firstLevelFolder = (folders.hasNext()) ? folders.next() : DriveApp.createFolder(firstLevelFolderName);

    /* Find the user-specific folder, create if the folder does not exist */
    var dropbox = form.myName + " " + form.myEmail;    /* Name of the Drive folder where the files should be saved */    
    folders = DriveApp.getFoldersByName(dropbox);
    var folder = (folders.hasNext()) ? folders.next() : firstLevelFolder.createFolder(dropbox); 

    /* Get the file uploaded though the form as a blob */
    var blob = form.myFile;    
    var file = folder.createFile(blob);    

    /* Set the file description as the name of the uploader */
    file.setDescription("Uploaded by " + form.myName);

    /* Return the download URL of the file once its on Google Drive */
    return "File uploaded successfully " + file.getUrl();

  } catch (error) {

    /* If there's an error, show the error message */
    return error.toString();
  }

}