phpgoogle-drive-api

Saving a file using Google Drives API to a specific location


I have a PHP app that saves some information into a .CSV file. I want to upload it to my Google Drive.

This seems to upload the file:

$service = new Google_Service_Drive($client);

$fileMetadata = new Google_Service_Drive_DriveFile(array(
    'name'      => 'file.csv',
    'parents'    => [$FOLDER_ID]
));

$file = $service->files->create($fileMetadata, array(
    'data' => $product_data,
    'mimeType' => 'application/octet-stream',
    'uploadType' => 'multipart',
    'fields' => 'id'
));

This has some weird issues:

  1. To upload it to a specific folder, I have to know the FILE ID, as opposed to simply adding the path.

  2. It will continuously add files with the same name instead of overwriting the file.

After some research, I can use $service->files->update to overwrite the existing file. However, to do that, I would need to know the $file_id.

Is there a way to upload files using the path, as opposed to IDS? Is there a way to create the file if it doesn't exist, or overwrite it if it does?

I can only think of two ways to do this:

  1. Hardcode the file name and DIR ids, then update it if it ever changes.
  2. Write code that scans the drive to figure out if the folder and file ids

I am adapting from the Dropbox API, which comparatively was much more intuitive.

Any help is appreciated - thanks


Solution

  • Save file in a specific folder using folder name

    After spending time exploring the Google Drive API, I was not able to find a way to directly to save a file to a specific folder by providing the path of the folder, however, I have found a possible alternative way of accomplising the same desired result by providing the name of the folder as a parameter of files.list method to retrive the folder id and then use it in the file.update method to achieve the other goal of overwriting a file inside the folder.

    Sample Code

    GET [https://www.googleapis.com/drive/v3/files?q=name%3D'asd'&key=[YOUR_API_KEY]](https://www.googleapis.com/drive/v3/files?q=name%3D'asd'&key=%5BYOUR_API_KEY%5D) HTTP/1.1
    
    Authorization: Bearer [YOUR_ACCESS_TOKEN] 
    Accept: application/json
    

    Sample Output

    {
      "kind": "drive\#fileList",
      "incompleteSearch": false,
      "files":
      [
        {
          "kind": "drive\#file",
          "mimeType": "application/vnd.google-apps.folder",
          "id": "1MYKnoK187EnkJpVQ\_N8z0PkNeK9Px6Gp",
          "name": "asd"
        }
      ]
    }
    

    Note:

    I tested this approach using Google API Explorer

    References:

    Drive API

    Method: files.list