Remove Google Form Submitted File

微笑、不失礼 提交于 2019-12-11 07:26:48

问题


WORKING CODE HERE: https://jsfiddle.net/nateomardavis/e0317gb6/

ORIGINAL QUESTION BELOW

How do I remove a form-submitted file from Drive itself?

I'm having trouble sorting out why a google form is submitting files to both my drive (not in a folder) but also into an auto-generated submission folder.

I've been able to move the renamed file to a new folder and delete the copy in the auto-generated submission folder. I cannot figure out how to remove the copy that's just listed in "Drive", not in any folder.

THE PROCESS (EDIT)

Let me try to explain the process more. I have a form that collects files. Google automatically makes a folder and sub-folders. I have successfully renamed the submitted files, moved them to a new folder, and deleted them from the Google-generated folder. However, a copy of the original, unchanged file is going to Google Drive, the root folder. Steps 1-3 (below) work as expected. Step 4 is where I'm running into issues.

  1. The original file being uploaded to a form. Note the file name.

  2. The Google-generated folder. The file is submitted this folder.

  3. The renamed file in a new folder. The original file is deleted from the folder above.

  4. The original file is now showing up in Drive, not in a folder but there. The name of this file is the same as the originally uploaded one. The one which went to the "passes" folder and was then deleted from that folder.

SNIPPET

//RENAME PASSES
if (itemResponses[f].getItem().getTitle() == "PASSES") { 
var files = itemResponses[f].getResponse();
//Logger.log(files.length);
if (files.length > 0) {
  for (var n in files) {
    var dFile = DriveApp.getFileById(files[n]);
    dFile.setName("LSS - " + year + " - " + teamName + " - " + "PASSES - " + today );
    teamFolder.addFile(dFile);   //MOVE SUBMITTED DOCUMENTS TO THAT FOLDER
    passesFolder.removeFile(dFile); //REMOVE FROM SUBMISSION FOLDER
    DriveApp.getRootFolder().removeFile(dFile) // (DOES NOT WORK) REMOVE FROM DRIVE FOLDER
    DriveApp.removeFile(dFile) // (DOES NOT WORK) REMOVE FROM DRIVE FOLDER
  }
}

FULL CODE

function getLastResponse() {

  var form = FormApp.openById('ID');

  var today = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "MM/dd/yyyy hh:mm a");
  var year = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "YYYY");
  Logger.log(today);

  var formResponses = form.getResponses();
  //Logger.log(formResponses.length);
  var formResponse = formResponses[formResponses.length-1];
  var respondentEmail = formResponse.getRespondentEmail()
  var itemResponses = formResponse.getItemResponses();
  Logger.log(itemResponses.length);
  var teamName = itemResponses[2].getResponse();
  //Logger.log("team name: " + teamName);


  //CHECK FOLDERS
   var dropbox = "Lititz Summer Showcase Team Check In (File responses)";
    var folder, folders = DriveApp.getFoldersByName(dropbox);

    var teamBox = teamName;
    var teamFolder, teamFolders = DriveApp.getFoldersByName(teamBox);

    var passesFolder = DriveApp.getFolderById('ID');
    var rosterFolder = DriveApp.getFolderById('ID');
    var teamInfoFolder = DriveApp.getFolderById('ID');
    var permissionToTravelFolder = DriveApp.getFolderById('ID');

    if (folders.hasNext()) { //CHECK IF DRIVE HAS FOLDER FOR FORM
      folder = folders.next();
    } else { //IF NOT CREATE FOLDER
      folder = DriveApp.createFolder(dropbox);
    }

    if (teamFolders.hasNext()) {  //CHECK IF FOLDER FOR TEAM EXISTS 
      teamFolder = teamFolders.next();
    } else { //IF NOT CREATE FOLDER
      teamFolder = folder.createFolder(teamBox);
      teamFolder.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.COMMENT);
    }

for (var f = 0; f < itemResponses.length; f++) {
    Logger.log(itemResponses[f].getItem().getType());
    Logger.log(itemResponses[f].getItem().getTitle());
  if (itemResponses[f].getItem().getType() == "FILE_UPLOAD") {
    Logger.log("THERE IS A FILE UPLOAD");

    //RENAME PASSES
    if (itemResponses[f].getItem().getTitle() == "PASSES") { 
    var files = itemResponses[f].getResponse();
    //Logger.log(files.length);
    if (files.length > 0) {
      for (var n in files) {
        var dFile = DriveApp.getFileById(files[n]);
        dFile.setName("LSS - " + year + " - " + teamName + " - " + "PASSES - " + today );
        teamFolder.addFile(dFile);   //MOVE SUBMITTED DOCUMENTS TO THAT FOLDER
        passesFolder.removeFile(dFile); //REMOVE FROM SUBMISSION FOLDER
        DriveApp.removeFile(dFile); // REMOVE FROM DRIVE FOLDER
      }
    }
    //RENAME ROSTER
    } else if (itemResponses[f].getItem().getTitle() == "ROSTER") {
      var files = itemResponses[f].getResponse();
    //Logger.log(files.length);
    if (files.length > 0) {
      for (var n in files) {
        var dFile = DriveApp.getFileById(files[n]);
        dFile.setName("LSS - " + year + " - " + teamName + " - " + "ROSTER - " + today );
        teamFolder.addFile(dFile);

      }
    }
   //RENAME TEAM INFO SHEET
   } else if (itemResponses[f].getItem().getTitle() == "TEAM INFO SHEET") {
      var files = itemResponses[f].getResponse();
    //Logger.log(files.length);
    if (files.length > 0) {
      for (var n in files) {
        var dFile = DriveApp.getFileById(files[n]);
        dFile.setName("LSS - " + year + " - " + teamName + " - " + "TEAM INFO SHEET - " + today );
        teamFolder.addFile(dFile);
      }
    }

  //RENAME PERMISSION TO TRAVEL
  } else if (itemResponses[f].getItem().getTitle() == "PERMISSION TO TRAVEL") {
      var files = itemResponses[f].getResponse();
    //Logger.log(files.length);
    if (files.length > 0) {
      for (var n in files) {
        var dFile = DriveApp.getFileById(files[n]);
        Logger.log(ownerEmail);
        dFile.setName("LSS - " + year + " - " + teamName + " - " + "PERMISSION TO TRAVEL - " + today );
        teamFolder.addFile(dFile);
      }
    }
    }
}//END 'IF FILE UPLOAD'
}//END FOR LOOP


}//END FUNCTION

回答1:


How about this answer?

Issue:

The flow of upload from Google Form is as follows.

  1. When the file is uploaded in the Form, the file is created to root folder.
  2. When the form is submitted, the file in the root folder is copied by renaming the filename to the folder created by the form.

In above case, the file in root folder is different from the file in the folder created by Google Form. By this, DriveApp.getRootFolder().removeFile(dFile) in your "SNIPPET" didn't work. This is the reason of your issue of script.

Workaround:

  • You want to delete the file remained in the root folder.

In order to delete the file created in the root folder, how about this workaround?

Unfortunately, the original filename cannot be retrieved from the form response. But the file which was copied to the folder created by the form has the filename of the format like {original filename} - ####.{extension}. In this workaround, the original filename is retrieved from this filename, and move the file to the trash using the retrieved original filename.

Sample script:

This sample script is run by the installable form submit trigger. So when the form was submitted, the script is run and the uploaded file is moved to the destination folder and the original file in the root folder is moved to the trash.

Before run the script:

In this sample script, it supposes that the script is the container-bound script of Google Form. Please be careful this.

  1. After cope and paste the script to the script editor, please set the destination folder ID to the script.
  2. please install the installable form submit trigger. If the trigger has already been installed, please remove it and install again.
  3. Please upload and submit a file using Google Form. By this, the script is run.

Script:

function formsubmit(e) {
  var destFolderId = "###"; // Destination folder ID

  if (e) {
    Utilities.sleep(3000); // This is required.
    var destfolder = DriveApp.getFolderById(destFolderId);
    var items = e.response.getItemResponses();
    for (var i = 0; i < items.length; i++) {
      if (items[i].getItem().getType() == "FILE_UPLOAD") {
        var files = items[i].getResponse();
        for (var j = 0; j < files.length; j++) {
          var file = DriveApp.getFileById(files[j]);
          var filename = file.getName();

          // Move uploaded file to the destination folder.
          var uploadedFile = DriveApp.getFileById(files[j]);
          var sourcefolder = uploadedFile.getParents().next();
          destfolder.addFile(file);
          sourcefolder.removeFile(file);

          // Retrieve original filename.
          var p1 = filename.split(" - ");
          var extension = p1[p1.length - 1];
          p1.pop();
          var name = p1.join(" - ");
          var p2 = "";
          if (extension.indexOf(".") > -1) {
            p2 = "." + extension.split(".")[1];
          }
          var orgFilename = name + p2;

          // Move uploaded file to the trash.
          var orgFiles = DriveApp.getRootFolder().getFilesByName(orgFilename);
          if (orgFiles.hasNext()) {
            var orgFile = orgFiles.next();
            orgFile.setTrashed(true);
          }
        }
      }
    }
  } else {
    throw new Error("This sample script is run by the installable form submit trigger.");
  }
}

Note:

  • This is a simple sample script for explaining this workaround. So please modify this for your situation.
  • In my environment, it was found Utilities.sleep(3000) was required. When the file is uploaded and the file is copied, the installable form submit trigger is run. At this time, if Utilities.sleep(3000) is not used, the file is moved before copying file is completed. By this, an error occurs. So I used it.
    • But I'm not sure whether the wait time of 3 seconds is the best. So if in your environment, an error occurs, please modify this.
    • I think that when a large file is uploaded, this value might be required to be large. Or also I think that running the script by the time-driven trigger might be better.
  • In this sample script, I used the installable form submit trigger. And when the form is submitted, the original file in the root folder is moved to the trash.
    • But I think that you can also run the script by the time-driven trigger. In this case, you can retrieve the response items by opening the form. About this, please select for your situation.

References:

  • Installable Triggers
  • setTrashed(trashed)
  • sleep(milliseconds)


来源:https://stackoverflow.com/questions/56171896/remove-google-form-submitted-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!