adamjamesb
adamjamesb

Reputation: 35

Google Form Script to create new folder and move images to it

I am looking for a script that, once a new image file(s) is uploaded to my Google Drive (via Google Form image upload, the script will create a folder based off one of these Google Form fields (for example Name), and then move all of the images to that folder.

This is what I've cobbled together so far, but because the folder will be generated based off a field I'm not sure how this would work.

function moveFiles() {
  var sourceFolder = DriveApp.getFolderById("Creative Upload (File responses)")

  var targetFolder = DriveApp.getFolderById("yyyyyyy") //what should this be?
  var files = sourceFolder.getFilesByType(MimeType.JPEG);
  while (files.hasNext()) {
    var file = files.next();
    targetFolder.addFile(file);  
    file.getParents().next().removeFile(file);
  }
}

Any suggestions would be greatly appreciated.

Upvotes: 0

Views: 985

Answers (1)

ziganotschka
ziganotschka

Reputation: 26806

You need to incorporate FormApp

  • Create a bound script attached to your form and retrieve the latest form submission.
  • Retrieve the response of interest (e.g. name) and use it to create a folder with this name.
  • Retrieve the Id of the folder.
  • Retrieve the Id of the uploaded image and add the image by its Id to the newly created folder.

Sample:

function myFunction() {
  var form=FormApp.getActiveForm();
  var length=form.getResponses().length;
  var name=form.getResponses()[length-1].getItemResponses()[0].getResponse();
  var uploadedImageId=form.getResponses()[length-1].getItemResponses()[1].getResponse();
  Logger.log(id);
  var file=DriveApp.getFileById(uploadedImageId);
  var folderId=DriveApp.createFolder(name).getId();
  DriveApp.getFolderById(folderId).addFile(file);
}

To run the script automatically on every form submission - bind your function to an installable trigger onFormSubmit.

Upvotes: 1

Related Questions