Headless Google Drive Uploads

Uploading files to Google Drive from the command line without any fancy agents, exotic libraries, dependencies should be simple. And here’s how it’s done…

First of all we need an Access Token for the Google Drive account we’re uploading to. This can be attained in many different ways. I’ve written a simple bash script to get Google API authentication and access tokens, which can be found here. Note: due to a bug somewhere, Google doesn’t seem to like drive scopes, so I’m using the all-enveloping https://docs.google.com/feeds for now.

Once you have you Access Token, calling the Google Drive API is simple using mere cURL. Multipart uploads allow you to inject metadata along with your file data in one request.

In short, you make a PUT or POST request to https://www.googleapis.com/upload/drive/v2/files/?uploadType=multipart, with an Authorization: Bearer $ACCESS_TOKEN header, and a Content-Type: multipart/related; boundary=$BOUNDARY content type.

The payload should look like so:

Content-Type: application/json; charset=UTF-8

{ "title": "My document", "parents": [ { "id": "xxxxxxxxx" } ] }

Content-Type: application/text



The whole script can be found here: https://github.com/soulseekah/bash-utils/blob/master/google-drive-upload/upload.sh. As you can see, we feed the whole file from stdin along with the necessary boundaries.

The “parents” argument “id” should be set to the ID of a folder in Google Drive. If left empty, the file will be uploaded to the root folder. You can get the ID from the URL in your Google Drive when visiting a folder. A list of mime-types for the file can be found in this stackoverflow answer.

Hope this helps folks out there that want to upload files to Google Drive from the command line.