Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get get the "shareable link" of a Google Drive file via Google Apps Script?

I thought it would be easy to get the shareable link for a file, like file.getShareableLink() but it seems that things are not so simple.

I've come across similar posts here but nothing that I can understand (alternativeLink and Shareable link for Google Drive file).

Is there really no straightforward way to do this? I've got hundreds of images to extract a shareable link for so they can be displayed online.

like image 299
MrGreggles Avatar asked Jul 09 '17 04:07

MrGreggles


2 Answers

How about following sample script? In this sample, it retrieves shared URLs of images in a specific folder.

Sample Script :

function myFunction() {
  var folderId = "### Specific folder ID ###";
  var files = DriveApp.getFolderById(folderId).getFiles();
  var result = [];
  while (files.hasNext()) {
      var file = files.next();
      file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
      var temp = {
        file_name: file.getName(),
        url: "http://drive.google.com/uc?export=view&id=" + file.getId(),
      };
      result.push(temp);
  };
  Logger.log(JSON.stringify(result))
}

Result :

[
  {
    "file_name": "filename1",
    "url": "http://drive.google.com/uc?export=view&id=### file ID 1###"
  },
  {
    "file_name": "filename2",
    "url": "http://drive.google.com/uc?export=view&id=### file ID 2###"
  }
]

Flow :

  1. Retrieve files in a folder which was set by folderId.

  2. Modify the permission of files. By this, users who don't login can also see the files. Only users who know the URLs can see them.

  3. Retrieve filename and file ID. And Retrieve file URLs using file ID. The URLs are the direct links for images.

    In this sample, folders in the folder cannot be checked. If you also want to check folders in the folder which was set by folderId, please tell me.

If I misunderstand your question, I'm sorry.

like image 130
Tanaike Avatar answered Sep 19 '22 23:09

Tanaike


A simplistic way is to add '&export=download' to your sharable link will download file with its file name.

Example : https://drive.google.com/uc?id=2xK9eHcBAjJJygtcyYtiQBwX-tt&export=download

like image 21
Codex Avatar answered Sep 22 '22 23:09

Codex