(JavaScript) List Files in Google Drive
Demonstrates how to list files in Google Drive.
See Google Drive Files list for more optional HTTP parameters.
var success = false;
success = true;
// It requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// This example uses a previously obtained access token having permission for the
// Google Drive scope.
var gAuth = new CkAuthGoogle();
gAuth.AccessToken = "GOOGLE-DRIVE-ACCESS-TOKEN";
var rest = new CkRest();
// Connect using TLS.
var bAutoReconnect = true;
success = rest.Connect("www.googleapis.com",443,true,bAutoReconnect);
// Provide the authentication credentials (i.e. the access token)
rest.SetAuthGoogle(gAuth);
// Get 4 results per page. (The default page size is 100, with a max of 1000.
rest.AddQueryParam("pageSize","4");
// This uses the Google Drive V3 API... (not V2)
var jsonResponse = rest.FullRequestNoBody("GET","/drive/v3/files");
if (rest.LastMethodSuccess !== true) {
console.log(rest.LastErrorText);
return;
}
// A successful response will have a status code equal to 200.
if (rest.ResponseStatusCode !== 200) {
console.log("request header = " + rest.LastRequestHeader);
console.log("response status code = " + rest.ResponseStatusCode);
console.log("response status text = " + rest.ResponseStatusText);
console.log("response header: " + rest.ResponseHeader);
console.log("response JSON: " + jsonResponse);
return;
}
// A successful response looks like this:
// {
// "kind": "drive#fileList",
// "files": [
// {
// "kind": "drive#file",
// "id": "0B53Q6OSTWYolenpjTEU4ekJlQUU",
// "name": "test",
// "mimeType": "application/vnd.google-apps.folder"
// },
// {
// "kind": "drive#file",
// "id": "0B53Q6OSTWYolRm4ycjZtdXhRaEE",
// "name": "starfish4.jpg",
// "mimeType": "image/jpeg"
// },
// {
// "kind": "drive#file",
// "id": "0B53Q6OSTWYolMWt2VzN0Qlo1UjA",
// "name": "hamlet2.xml",
// "mimeType": "text/xml"
// },
// ...
// {
// "kind": "drive#file",
// "id": "0B53Q6OSTWYolc3RhcnRlcl9maWxlX2Rhc2hlclYw",
// "name": "Getting started",
// "mimeType": "application/pdf"
// }
// ]
// }
// Iterate over each file in the response and show the name, id, and mimeType.
var json = new CkJsonObject();
json.Load(jsonResponse);
// Show the full JSON response.
json.EmitCompact = false;
console.log(json.Emit());
var numFiles = json.SizeOfArray("files");
var i = 0;
while (i < numFiles) {
json.I = i;
console.log("name: " + json.StringOf("files[i].name"));
console.log("id: " + json.StringOf("files[i].id"));
console.log("mimeType: " + json.StringOf("files[i].mimeType"));
console.log("-");
i = i+1;
}
|