Geoff
Geoff

Reputation: 6629

Google drive php get file name before download

Am downloading files from google drive which are images, some are png,jpeg or gif files. These files are uploaded via a google form which i then get the file id via the url from google form responses. I would like to get the original name or its extension. Currently am using the following code which works

   $response = $service->files->get($file_id, array(
                'alt' => 'media')); //service is the google drive service. file id is drive file id
   $upload_file_url = "/uploads/" . time() . "_image.jpg"; //assigning the file as .jpg 
          
  $outHandle = fopen("myFolder/" . $upload_file_url, "w+");

  while (!$response->getBody()->eof()) {
                fwrite($outHandle, $response->getBody()->read(1024));
   }
  fclose($outHandle);

The above works but some images are not jpg. Is it possible to get the $response file name or file extension to handle the non jpg file and save them with the correct extension/s

Upvotes: 0

Views: 1642

Answers (1)

Kristkun
Kristkun

Reputation: 5953

Files.get() is used to get a file's metadata or content by file id.

  • If alt=media URL parameter is NOT INCLUDED in the request, Files.get() will return a Files Resource which includes the file name and the file type/mime type.

  • If alt=media URL parameter is INCLUDED in the request, Files.get() will return the file content

Note:

If you did not set the fields optional query parameter in your request, the response includes a default set of fields specific to this method. Default includes the following upon checking the API explorer: kind, id, name and mimeType

Sample Code:

$file = $service->files->get($file_id); 
print "File Name: " . $file->getName();
print "Description: " . $file->getDescription();
print "MIME type: " . $file->getMimeType();

$response = $service->files->get($file_id, array(
                'alt' => 'media'));

You can check the mimeType to determine whether the file is jpg, png or gif using the following:

  • JPEG MimeType = "image/jpeg"

  • PNG MimeType = "image/png"

  • GIF MimeType = "image/gif"


Reference:

Upvotes: 1

Related Questions