Skip to content

Commit d3c9791

Browse files
authored
adds Large File Download example (#1127)
1 parent e39fe36 commit d3c9791

5 files changed

Lines changed: 204 additions & 1 deletion

File tree

examples/index.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
<li><a href="service-account.php">A query using the service account functionality.</a></li>
3737
<li><a href="simple-file-upload.php">An example of a small file upload.</a></li>
3838
<li><a href="large-file-upload.php">An example of a large file upload.</a></li>
39+
<li><a href="large-file-download.php">An example of a large file download.</a></li>
3940
<li><a href="idtoken.php">An example of verifying and retrieving the id token.</a></li>
4041
<li><a href="multi-api.php">An example of using multiple APIs.</a></li>
4142
</ul>

examples/large-file-download.php

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
<?php
2+
/*
3+
* Copyright 2011 Google Inc.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
include_once __DIR__ . '/../vendor/autoload.php';
19+
include_once "templates/base.php";
20+
21+
echo pageHeader("File Download - Downloading a large file");
22+
23+
/*************************************************
24+
* Ensure you've downloaded your oauth credentials
25+
************************************************/
26+
if (!$oauth_credentials = getOAuthCredentialsFile()) {
27+
echo missingOAuth2CredentialsWarning();
28+
return;
29+
}
30+
31+
/************************************************
32+
* The redirect URI is to the current page, e.g:
33+
* http://localhost:8080/large-file-download.php
34+
************************************************/
35+
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
36+
37+
$client = new Google_Client();
38+
$client->setAuthConfig($oauth_credentials);
39+
$client->setRedirectUri($redirect_uri);
40+
$client->addScope("https://www.googleapis.com/auth/drive");
41+
$service = new Google_Service_Drive($client);
42+
43+
/************************************************
44+
* If we have a code back from the OAuth 2.0 flow,
45+
* we need to exchange that with the
46+
* Google_Client::fetchAccessTokenWithAuthCode()
47+
* function. We store the resultant access token
48+
* bundle in the session, and redirect to ourself.
49+
************************************************/
50+
if (isset($_GET['code'])) {
51+
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
52+
$client->setAccessToken($token);
53+
54+
// store in the session also
55+
$_SESSION['upload_token'] = $token;
56+
57+
// redirect back to the example
58+
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
59+
}
60+
61+
// set the access token as part of the client
62+
if (!empty($_SESSION['upload_token'])) {
63+
$client->setAccessToken($_SESSION['upload_token']);
64+
if ($client->isAccessTokenExpired()) {
65+
unset($_SESSION['upload_token']);
66+
}
67+
} else {
68+
$authUrl = $client->createAuthUrl();
69+
}
70+
71+
/************************************************
72+
* If we're signed in then lets try to download our
73+
* file.
74+
************************************************/
75+
if ($client->getAccessToken()) {
76+
// Check for "Big File" and include the file ID and size
77+
$files = $service->files->listFiles([
78+
'q' => "name='Big File'",
79+
'fields' => 'files(id,size)'
80+
]);
81+
82+
if (count($files) == 0) {
83+
echo "
84+
<h3 class='warn'>
85+
Before you can use this sample, you need to
86+
<a href='/large-file-upload.php'>upload a large file to Drive</a>.
87+
</h3>";
88+
return;
89+
}
90+
91+
// If this is a POST, download the file
92+
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
93+
// Determine the file's size and ID
94+
$fileId = $files[0]->id;
95+
$fileSize = intval($files[0]->size);
96+
97+
// Get the authorized Guzzle HTTP client
98+
$http = $client->authorize();
99+
100+
// Open a file for writing
101+
$fp = fopen('Big File (downloaded)', 'w');
102+
103+
// Download in 1 MB chunks
104+
$chunkSizeBytes = 1 * 1024 * 1024;
105+
$chunkStart = 0;
106+
107+
// Iterate over each chunk and write it to our file
108+
while ($chunkStart < $fileSize) {
109+
$chunkEnd = $chunkStart + $chunkSizeBytes;
110+
$response = $http->request(
111+
'GET',
112+
sprintf('/drive/v3/files/%s', $fileId),
113+
[
114+
'query' => ['alt' => 'media'],
115+
'headers' => [
116+
'Range' => sprintf('bytes=%s-%s', $chunkStart, $chunkEnd)
117+
]
118+
]
119+
);
120+
$chunkStart = $chunkEnd + 1;
121+
fwrite($fp, $response->getBody()->getContents());
122+
}
123+
// close the file pointer
124+
fclose($fp);
125+
126+
// redirect back to this example
127+
header('Location: ' . filter_var($redirect_uri . '?downloaded', FILTER_SANITIZE_URL));
128+
}
129+
}
130+
?>
131+
132+
<div class="box">
133+
<?php if (isset($authUrl)): ?>
134+
<div class="request">
135+
<a class='login' href='<?= $authUrl ?>'>Connect Me!</a>
136+
</div>
137+
<?php elseif(isset($_GET['downloaded'])): ?>
138+
<div class="shortened">
139+
<p>Your call was successful! Check your filesystem for the file:</p>
140+
<p><code><?= __DIR__ . DIRECTORY_SEPARATOR ?>Big File (downloaded)</code></p>
141+
</div>
142+
<?php else: ?>
143+
<form method="POST">
144+
<input type="submit" value="Click here to download a large (20MB) test file" />
145+
</form>
146+
<?php endif ?>
147+
</div>
148+
149+
<?= pageFooter(__FILE__) ?>

examples/large-file-upload.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,7 @@ function readVideoChunk ($handle, $chunkSize)
157157
<div class="shortened">
158158
<p>Your call was successful! Check your drive for this file:</p>
159159
<p><a href="https://drive.google.com/open?id=<?= $result->id ?>" target="_blank"><?= $result->name ?></a></p>
160+
<p>Now try <a href="/large-file-download.php">downloading a large file from Drive</a>.
160161
</div>
161162
<?php else: ?>
162163
<form method="POST">

tests/examples/indexTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public function testIndex()
2626
$crawler = $this->loadExample('index.php');
2727

2828
$nodes = $crawler->filter('li');
29-
$this->assertEquals(8, count($nodes));
29+
$this->assertEquals(9, count($nodes));
3030
$this->assertEquals('A query using simple API access', $nodes->first()->text());
3131
}
3232
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<?php
2+
/**
3+
* Licensed to the Apache Software Foundation (ASF) under one
4+
* or more contributor license agreements. See the NOTICE file
5+
* distributed with this work for additional information
6+
* regarding copyright ownership. The ASF licenses this file
7+
* to you under the Apache License, Version 2.0 (the
8+
* "License"); you may not use this file except in compliance
9+
* with the License. You may obtain a copy of the License at
10+
*
11+
* http://www.apache.org/licenses/LICENSE-2.0
12+
*
13+
* Unless required by applicable law or agreed to in writing,
14+
* software distributed under the License is distributed on an
15+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16+
* KIND, either express or implied. See the License for the
17+
* specific language governing permissions and limitations
18+
* under the License.
19+
*/
20+
21+
class examples_largeFileDownloadTest extends BaseTest
22+
{
23+
public function testSimpleFileDownloadNoToken()
24+
{
25+
$this->checkServiceAccountCredentials();
26+
27+
$crawler = $this->loadExample('large-file-download.php');
28+
29+
$nodes = $crawler->filter('h1');
30+
$this->assertEquals(1, count($nodes));
31+
$this->assertEquals('File Download - Downloading a large file', $nodes->first()->text());
32+
33+
$nodes = $crawler->filter('a.login');
34+
$this->assertEquals(1, count($nodes));
35+
$this->assertEquals('Connect Me!', $nodes->first()->text());
36+
}
37+
38+
public function testSimpleFileDownloadWithToken()
39+
{
40+
$this->checkToken();
41+
42+
global $_SESSION;
43+
$_SESSION['upload_token'] = $this->getClient()->getAccessToken();
44+
45+
$crawler = $this->loadExample('large-file-download.php');
46+
47+
$buttonText = 'Click here to download a large (20MB) test file';
48+
$nodes = $crawler->filter('input');
49+
$this->assertEquals(1, count($nodes));
50+
$this->assertEquals($buttonText, $nodes->first()->attr('value'));
51+
}
52+
}

0 commit comments

Comments
 (0)