2016/11/04

Google Drive API - Listing all files on a client's Google Drive using JavaScipt

The code below runs on a web sever and it lists all files on Google Drive. Be sure to put in your client id (highlighted in yellow below) before running it.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
  <head>
    <script type="text/javascript">
      var CLIENT_ID = '<YOUR CLIENT ID>'; 
      var SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];

      function checkAuth() {
        gapi.auth.authorize(
          {
            'client_id': CLIENT_ID,
            'scope': SCOPES.join(' '),
            'immediate': true
          }, handleAuthResult);
      }

      function handleAuthResult(authResult) {
        var authorizeDiv = document.getElementById('authorize-div');
        if (authResult && !authResult.error) {
          authorizeDiv.style.display = 'none';
          loadDriveApi();
        } else {
          authorizeDiv.style.display = 'inline';
        }
      }

      function handleAuthClick(event) {
        gapi.auth.authorize(
          {client_id: CLIENT_ID, scope: SCOPES, immediate: false},
          handleAuthResult);
        return false;
      }

      function loadDriveApi() {
        gapi.client.load('drive', 'v3', listFiles);
      }

      function listFiles() {
        var request = gapi.client.drive.files.list({
            //'pageSize': 20,
            'fields': "nextPageToken, files(id, name)"
          });

          request.execute(function(resp) {
            appendPre('Files:');
            var files = resp.files;
            if (files && files.length > 0) {
              for (var i = 0; i < files.length; i++) {
                var file = files[i];
                appendPre(file.name + ' (' + file.id + ')');
              }
            } else {
              appendPre('No files found.');
            }
          });
      }

      function appendPre(message) {
        var pre = document.getElementById('output');
        var textContent = document.createTextNode(message + '\n');
        pre.appendChild(textContent);
      }

    </script>
    <script src="https://apis.google.com/js/client.js?onload=checkAuth">
    </script>
  </head>
  <body>
    <div id="authorize-div" style="display: none">
      <span>Authorize access to Drive API</span>
      <button id="authorize-button" onclick="handleAuthClick(event)">
        Authorize
      </button>
    </div>
    <pre id="output"></pre>
  </body>
</html>

Result


Reference:

JavaScript Quickstart
https://developers.google.com/drive/v3/web/quickstart/js

No comments:

Post a Comment