Search code examples
google-apps-scriptgoogle-forms

No item with the given ID can be found onSubmit Google Form


I created a script that runs onSubmit on a Google Form. It should get the ID of the image uploaded to the form, get the Image as Blob and then forward it to some email adress. The thing is, is that sometimes (about 1 in 10), the script gives the following error:

Exception: No item with the given ID could be found, or you do not have permission to access it. at on_Submit(Code:6:24)

I figured it would have to do with the time it takes Google to Upload/Move the file into Drive, so I set a timeout to give it some time. The error still appears, a little less frequent. Does anyone understand where this could go wrong?

The code:

function on_Submit(e) {
  Utilities.sleep(30 * 1000)
  var res  = e.response
  var image_id = res.getItemResponses()[0].getResponse()

  var image = DriveApp.getFileById(image_id).getBlob()}

The on_Submit(e) function is linked to a manual trigger to enable the use of DriveApp. Thanks


Solution

  • Some of the responses turned out to have multiple file uploads. The response to that question was an array of ID's. Here's the correct code:

    Utilities.sleep(30 * 1000)
      var res  = e.response
      var image_id = res.getItemResponses()[0].getResponse()
      console.log(image_id)
      if(Array.isArray(image_id)){
        var images = [];
        for(var i in image_id){
          var id = image_id[i]
          var image = DriveApp.getFileById(id).getBlob()
          images.push(image)
        }
        console.log(images)
        GmailApp.sendEmail(SOME_EMAIL, SUBJECT, BODY, {attachments: images})
      }
      else{
        var image = DriveApp.getFileById(image_id).getBlob()
        GmailApp.sendEmail(SOME_EMAIL, SUBJECT, BODY, {attachments: [image]})
      }