Open Files
The Google Drive UI provides two ways to open files:
- The Open with contextual menu item
- The Google Picker dialog for opening files
To see what these UI features look like, check the overview of What Can You Do with the Drive SDK?. The rest of this page describes how to integrate your app with these Drive UI features to open files stored in Google Drive.
Open files using the Open with contextual menu
When a user chooses files in Google Drive and selects the Open with menu option,
Drive redirects the user to the Open URL for the selected application (this URL is defined when you
enable the Drive SDK). The redirected request
from the user's browser contains this important information in the state
parameter:
- The ID of the file(s) to open.
- The
action
, set toopen
.
You'll need the file ID to fetch file metadata and download file content. The state parameter is URL-encoded, so you'll need to handle the escape characters and parse it as JSON. In JSON notation, state information for an Open with URL looks like the following:
{
"ids": ["0Bz0bd"],
"action":"open",
}
The following example illustrates how to load state information using the supported client libraries.
Java
/** * An object representing the state parameter passed into this application * from the Drive UI integration (i.e. Open With or Create New). Required * for Gson to deserialize the JSON into POJO form. * */ public class State { /** * Action intended by the state. */ public String action; /** * IDs of files on which to take action. */ public Collection<String> ids; /** * Parent ID related to the given action. */ public String parentId; /** * Empty constructor required by Gson. */ public State() {} /** * Create a new State given its JSON representation. * * @param json Serialized representation of a State. */ public State(String json) { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); State other = gson.fromJson(json, State.class); this.action = other.action; this.ids = other.ids; this.parentId = other.parentId; } }
Python
class DriveState(object): """Store state provided by Drive.""" def __init__(self, state): """Create a new instance of drive state. Parse and load the JSON state parameter. Args: state: State query parameter as a string. """ state_data = json.loads(state) self.action = state_data['action'] self.ids = map(str, state_data.get('ids', []))
PHP
/* * Check to see if the 'state' parameter exists, with * the mode and specified file IDs (on open) or a folder parentId * (on create). */ /* * State should always be defined */ if (isset($_GET['state'])) { $state = json_decode(stripslashes($_GET['state'])); $_SESSION['mode'] = $state->action; if (isset($state->ids)){ $_SESSION['fileIds'] = $state->ids; } else { $_SESSION['fileIds'] = array(); } if (isset($state->parentId)) { $_SESSION['parentId'] = $state->parentId; } else { $_SESSION['parentId'] = null; } } else { $error = 'Code defined, but no state. Condition shouldn\'t exist.'; throw new Exception($error); } }
.NET
public ActionResult Index(string state, string code) { ... DriveState driveState = new DriveState(); if (!string.IsNullOrEmpty(state)) { JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); driveState = jsonSerializer.Deserialize<DriveState>(state); } if (driveState.action == "open") { return OpenWith(driveState); } else { return CreateNew(driveState); } } public class DriveState { public string action { get; set; } public string parentId { get; set; } public string[] ids { get; set; } }
Ruby
# Parse the state as JSON if present s = params[:state] || '{}' state = MultiJson.decode(s) # Check action... if state['action'] == 'create' # Create a new file parent_id = state['parentId'] else # Open one or more files file_ids = state['ids'] end
Once it has the file ID and an access token, an app can check permissions, fetch the file metadata, and download the file content as described in the reference documentation for files.get.
Open and convert Google Docs in your app
An app registered with the Import option enabled in the APIs Console can import supported Google Doc formats. This means that if a user selects Open with for a Google doc, the app can convert it to a format that the app can handle. When Open with triggers a conversion this way, Drive evaluates the MIME types an app can open (set during registration) and extrapolates the list of formats that the app can import.
Google Doc formats and supported export MIME types map to each other as follows:
Google Doc Format | Conversion Format | Corresponding MIME type |
---|---|---|
Documents | HTML | text/html |
Plain text | text/plain | |
Rich text | application/rtf | |
Open Office doc | application/vnd.oasis.opendocument.text | |
application/pdf | ||
MS Word document | application/vnd.openxmlformats-officedocument.wordprocessingml.document | |
Spreadsheets | MS Excel | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
Open Office sheet | application/x-vnd.oasis.opendocument.spreadsheet | |
application/pdf | ||
Drawings | JPEG | image/jpeg |
PNG | image/png | |
SVG | image/svg+xml | |
application/pdf | ||
Presentations | MS PowerPoint | application/vnd.openxmlformats-officedocument.presentationml.presentation |
Open Office, PDF | application/pdf |
When a user selects an app from the Open with contextual menu for a Google Doc, Drive redirects the user to the Open URL for the selected application. The redirected request
from the user's browser contains this important information in the state
parameter:
- The
action
, set toopen
. - The
exportIds
to use.
Once it has the export IDs, an app can fetch the file metadata and extract the desired download URL
from the exportLinks
values. These are key-value pairs in which the key is a MIME type and the value is the
download URL for the converted file.
The app can download the converted file content from the download URL. Apps can display converted files as read-only, or let users save them as new files.
Open and Upload files using the Google Picker
If you want to let users open or upload Google Drive files directly from your web app independently of the Drive UI, you can use the Google Picker API. The picker can display a list of the currently authenticated user's Drive files in an interface like the following:
.
When a user selects a file from the list, the file ID is returned, and the ID may be used by your app to access the file. You can also add to a picker dialog the capability to upload files to Google Drive.
The following picker example illustrates an image selector/uploader page that could be opened from an Open or Upload Drive files button in a web app. This example demonstrates how to set the AppId
value, and incorporates some useful picker features such as enabling multi-select, hiding the navigation pane, and choosing the user account with the app's current OAuth 2.0 token:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Picker Example</title>
<!-- The standard Google Loader script; use your own key. -->
<script src="http://www.google.com/jsapi?key=AIzaSyBV6MeANy_ZaLB2f2c-XKCMA7hIu2Fy744"></script>
<script type="text/javascript">
// Use the Google Loader script to load the google.picker script.
google.setOnLoadCallback(createPicker);
google.load('picker', '1');
// Create and render a Picker object for searching images.
function createPicker() {
var view = new google.picker.View(google.picker.ViewId.DOCS);
view.setMimeTypes("image/png,image/jpeg,image/jpg");
var picker = new google.picker.PickerBuilder()
.enableFeature(google.picker.Feature.NAV_HIDDEN)
.enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
.setAppId(YOUR_APP_ID)
.setOAuthToken(AUTH_TOKEN) //Optional: The auth token used in the current Drive API session.
.addView(view)
.addView(new google.picker.DocsUploadView())
.setCallback(pickerCallback)
.build();
picker.setVisible(true);
}
// A simple callback implementation.
function pickerCallback(data) {
if (data.action == google.picker.Action.PICKED) {
var fileId = data.docs[0].id;
alert('The user selected: ' + fileId);
}
}
</script>
</head>
<body>
<div id="result"></div>
</body>
</html>
The AppId
set here and the client ID used for authorizing access to a user's files must be contained in the same app. These values are shown in the APIs console for a registered app.
After obtaining the file ID from the picker when opening files, an application can then fetch the file metadata and download the file content as described in the reference documentation for files.get.