google-apps-scriptgoogle-drive-apigoogle-formsgoogle-forms-api

I want to change the names of old files uploaded to Google Forms


I have a google form and all the files uploaded by the participants contain random names.

function renamefile() {
    var form = FormApp.openById('16aPNgaSuDZ-e0ibw08jW7_-YMULGWV-_iUP9uQHE'); //DDD
    var formResponses = form.getResponses();
    var baseString = 'https://drive.google.com/file/d/';
    var endString = '/view?usp=drivesdk';
        
    var folder = DriveApp.getFolderById('1BPA7wkECV1vOB6bo3tGfUZd9MifjwYJG2BVI_sHSeNojFY-xiN4dvLW_vc2zw4IEe');
    var files = folder.getFiles();

    while (files.hasNext()) {
        var file = files.next();
        for (var i = 0; i < formResponses.length; i++) {
            var formResponse = formResponses[i];
            var itemResponses = formResponse.getItemResponses();
            var itemResponseFname = itemResponses[1];
            var itemResponsePhoto = itemResponses[15];
            var photoID = itemResponsePhoto.getResponse();
            var newName = itemResponseFname.getResponse() +  " - " + "PHOTO"  ;
            var url = baseString + photoID + endString;
            var urlCheck = file.getUrl();
            
            if ( url == urlCheck) {
                var modName = newName + ".pdf" ;
                file.setName(modName);
            }
            
        }
    }
} 

Solution

  • Modification points:

    When these points are reflected in your script, how about the following modification?

    Modified script:

    function renamefile() {
      var form = FormApp.openById('###'); // Please set your file ID of Google Forms.
      var folder = DriveApp.getFolderById('###'); // Please set your folder ID.
    
      // Create an object for searching file ID.
      var obj = form.getResponses().reduce((o, f) => {
        var itemResponses = f.getItemResponses();
        var itemResponseFname = itemResponses[1];
        var itemResponsePhoto = itemResponses[15];
        var fileId = itemResponsePhoto.getResponse();
        var newName = itemResponseFname.getResponse() + " - " + "PHOTO";
        o[fileId] = newName + ".pdf";
        return o;
      }, {});
    
      // Rename files.
      var files = folder.getFilesByType(MimeType.PDF);
      while (files.hasNext()) {
        var file = files.next();
        var fileId = file.getId();
        if (obj[fileId]) {
          file.setName(obj[fileId]);
        }
      }
    }
    

    Note:

    Reference: