Reputation: 1301
Trying to get image URL instead of file content from Google Drive API. In the new version this GOOD thing is deprecated.
I searched a lot, on Google developer class there is a method, but its missing in the new version as well.
The problem is that I'm going to get lot of images from the Drive, but don't want to loose the speed of Google trying to path trough my app all images. And this is stupid also.
Is there a way to get those link somehow still?
This is my code I use to get file content:
$this->client = new \Google_Client();
$this->client->setAuthConfigFile('config.json');
$this->client->setScopes('https://www.googleapis.com/auth/drive');
if (isset($_GET['code'])) $code = $_GET['code'];
if(!isset($_SESSION['access_token'])){
if (!isset( $code )){
$auth_url = $this->client->createAuthUrl();
$filtered_url = filter_var($auth_url, FILTER_SANITIZE_URL);
return redirect($filtered_url);
}else{
$this->client->authenticate($_GET['code']);
$_SESSION['access_token'] = $this->client->getAccessToken();
// return redirect('/');
}
}
$this->service = new \Google_Service_Drive($this->client);
$file_id = '0B3vR4cBcxn4oNm9TSlBzcngyMzQ';
$results = $this->service->files->get($file_id, array('alt' => 'media'));
$imaga = $results->getBody()->getContents();
$imageData = base64_encode($imaga);
$contentType = $results->getHeader("content-type");
$src = 'data: '.$contentType[0].';base64,'.$imageData;
Upvotes: 4
Views: 7962
Reputation: 1620
I was stuck on the same problem using node.js and npm package googleapis (official package from google).
The following solution is not in PHP but concept should remain the same.
Although I'm late but it might help somebody else looking for a similar problem.
Node.js
var google = require('googleapis');
var OAuth2 = google.auth.OAuth2;
//setup your oauth credentials and tokens
oauth2Client.setCredentials(tokens);
var drive = google.drive({
version: 'v2',
auth: oauth2Client
});
drive.files.get({
fileId: fileId, //id of the file you are looking for
alt: 'media'
}, {
responseType: 'arraybuffer',
encoding: null
}, function(err, response) {
if (err) {
console.log(err);
//handle the error
} else {
var imageType = response.headers['content-type'];
var base64 = new Buffer(response.data, 'utf8').toString('base64');
var dataURI = 'data:' + imageType + ';base64,' + base64;
res.send(dataURI);
}
});
HTML
<img src="dataURI_received_from_above_HTTP_request"></img>
Upvotes: 2
Reputation: 17651
As of now, I think there's 2 ways you can access your Drive images with the API. That's using webContentLink
if you want to download the file and the webViewLink
if you want to display the file. Those are the available drive metadata you can use.
Upvotes: 2