Google scripts, get a drive file url

theone15247 picture theone15247 · Feb 27, 2014 · Viewed 11k times · Source

I need my script to load the URL of a drive file to be added to a spreadsheet. For whatever reason 'File.getUrl()' returns null, but everything else seems to be working.

For example, 'File.getName()' works. So am I missing a permission or something?

Here is my code (abridged):

function loadURL(folderPath, name) {       
  var folder = loadFolder(folderPath);

  // Find file
  var files = folder.searchFiles('modifiedDate >= "' + getDate() + '" and title = "' + name + '"'),
      file, found = 0;

  for (; files.hasNext(); found++) {
    file = files.next();
  }

  if (found == 1) {
    /////////////////////////////////
    // Here is 'getUrl'
    /////////////////////////////////
    var url = file.getUrl();

    Logger.log("Loaded: " + url);
    return url;
  } else {
    throw "Error loading file";
  }
}

/**
* ** NOTE: THIS SEEMS TO BE WORKING FINE **
* Load a folder
* @param {string} url
* @return {Folder}
*/
function loadFolder(url) {
  var folders = url.split('/'),
      folder = DriveApp.getRootFolder();

  Logger.log("Loading URL: " + url);

  for (var key in folders) {
    var fName = folders[key];    
    if (fName.length > 0) {
      var fIt = folder.getFoldersByName(fName),
          found = 0;

      Logger.log(" -> " + fName);

      for (; fIt.hasNext(); found++) {
        folder = fIt.next();
      }

      if (found == 0) {
        throw "Could not find the folder '" + fName + "'";
      } else if (found > 1) {
        throw "Found multiple matches to the folder '" + fName + "'";
      }
    }
  }

  return folder;
}

And the log if you're curious:

[14-02-26 19:56:15:980 EST] Loading URL: Work/PDF/
[14-02-26 19:56:15:981 EST]  -> Work
[14-02-26 19:56:16:120 EST]  -> PDF
[14-02-26 19:56:16:450 EST] Loaded: null

And if I change getUrl to getName it (kinda) works

[14-02-26 20:10:20:588 EST] Loading URL: Work/PDF/
[14-02-26 20:10:20:589 EST]  -> Work
[14-02-26 20:10:20:727 EST]  -> PDF
[14-02-26 20:10:21:058 EST] Loaded: Test

Answer

theone15247 picture theone15247 · Feb 27, 2014

Using the id instead of the url works:

var url = "https://docs.google.com/document/d/" + file.getId() + "/";