jgloves
jgloves

Reputation: 719

How to get ID value of Google Drive file for input to Google Apps Script

I am writing a Google Apps script to send a file from Google Drive to a list of email addresses saved in a Google Spreadsheet.

Since I will be sending a different file every time I use the script, I have my script set up to take the file ID as text input from the user. The only way I've seen to get the ID directly from Drive is to right-click on the file, select "Get Link", copy it to the clipboard, paste it into my form and erase the bits that aren't the ID. I'm writing to ask if anyone knows a better way. I'm also open to comments suggesting a better program design.

function sendEmails() {
  var id = "gibberish"; //email spreadsheet
  SpreadsheetApp.openById(id);
  var sheet = SpreadsheetApp.getActiveSheet();
  Logger.log(sheet.getName());
  var startRow = 2;  // First row of data to process
  var numRows = 2;   // Number of rows to process
  // Fetch the range of cells A2:B3
  var dataRange = sheet.getRange(startRow, 1, numRows, 2);
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();

  //Get subject line from user
  var ui = SpreadsheetApp.getUi();
  var response = ui.prompt('Enter subject: ', ui.ButtonSet.OK_CANCEL);

  var subject;
  // Process the user's response. TODO- error checking
  if (response.getSelectedButton() == ui.Button.OK) {
    subject = response.getResponseText(); 
  } else {
    Logger.log('The user either canceled or clicked the close button in the dialog\'s title bar.');
    subject = "No subject";
  }

  //get id for attachment file
  var ui2 = SpreadsheetApp.getUi();
  var response2 = ui2.prompt('Enter Drive id for attachment: ', ui.ButtonSet.OK_CANCEL); //TODO- error checking

  var attachmentID;
  var file = null;

  if (response2.getSelectedButton() == ui.Button.OK) {
    attachmentID = response2.getResponseText();
    file = DriveApp.getFileById(attachmentID);
    Logger.log('The user entered %s', response2.getResponseText());
  } else {
    Logger.log('The user either canceled or clicked the close button in the dialog\'s title bar.');
  }

  for (i in data) {
    var row = data[i];
    var emailAddress = row[0];  // First column
    var message = "Time Sheet attached. \n\n -Jessica";       
    if (file != null) { //TODO- or if file is right file
      MailApp.sendEmail(emailAddress, subject, message, {attachments: [file]});
    } else {
      Logger.log("No file was attached. Email not sent.");
    }
  }
}

Upvotes: 0

Views: 3052

Answers (2)

J. G.
J. G.

Reputation: 1832

This isn't mine, we've all passed it around this forum quite a bit.

this one works because it gets what you want regardless of if the person pastes in the id or the url:

function getIdFromUrl(url) { return url.match(/[-\w]{25,}/); }

so you don't need to be picky about erasing the rest of the url yourself.

Upvotes: 1

Eric Dauenhauer
Eric Dauenhauer

Reputation: 759

I did something similar in my Copy Folder script.

Basically, I parsed the form input in javascript to select only the folder ID. With this code, you can actually pass in the "Sharing ID" (retrieved by the Right-click and "Get Link" method), the folder URL (retrieved by the browser address bar when you are inside the folder in Google Drive), or just the folder ID. The javascript parses the input and replaces the form entry with just the folder ID, so that your Google Script can retrieve this form data normally.

You can view the source code for the project, but here is the relevant part. In my web app, this is located in the JavaScript.html file.

// Regular expression - find string beginning with "id="
// http://www.w3schools.com/jsref/jsref_regexp_source.asp
var regex = /id=/; 
// NOTE: pretty sure you could just make a string variable = "id=" instead of regex, but I didn't want to mess up my script

// Set a temporary variable to the value passed into the "folderId" field
var fId = thisForm.folderId.value;

// Get the index of the string at which the folderId starts
var idStart = fId.search(regex);
var foldersStart = fId.search("folders");
if (idStart > 0) {
// Slice the string starting 3 indices after "id=", which means that it takes away "id=" and leaves the rest
fId = fId.slice(idStart+3);  
} else if (foldersStart > 0) {
fId = fId.slice(foldersStart + 8);  
}

// Find the ampersand in the remaining string, which is the delimiter between the folderId and the sharing privileges
var amp = fId.indexOf("&");

// Slice the string up to the ampersand
if (amp > 0) {
fId = fId.slice(0,amp);
}

// Set the folderId element within thisForm (retrieved from doGet) to the new, sliced fId variable
thisForm.folderId.value = fId;

Upvotes: 0

Related Questions