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 platform?. 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 platform). The redirected request from the user's browser contains this important information in the state parameter:

  • The ids of the file(s) to open (or exportIds when opening native Google documents)
  • The action, set to open.
  • The userId of the authenticated user.

Instead of the state parameter, you may opt to use template variable substitution to construct the request URL instead.

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"],

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 Drive UI Integration tab within the Drive API in the API 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
PDF 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
PDF application/pdf
CSV (first sheet only) text/csv
Drawings JPEG image/jpeg
PNG image/png
SVG image/svg+xml
PDF application/pdf
Presentations MS PowerPoint application/vnd.openxmlformats-officedocument.presentationml.presentation
PDF application/pdf
Plain text text/plain
Apps Scripts JSON application/

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 to open.
  • The exportIds to use.

Once it has the export IDs, an app can fetch the file metadata to determine the mime type if necessary.

The app can also download the converted file content with the files.export method.


String fileId = "1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().export(fileId, "application/pdf")


file_id = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo'
request = drive_service.files().export_media(fileId=file_id,
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print "Download %d%%." % int(status.progress() * 100)


$fileId = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo';
$content = $driveService->files->export($fileId, 'application/pdf', array(
  'alt' => 'media' ));


var fileId = "1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo";
var request = driveService.Files.Export(fileId, "application/pdf");
var stream = new System.IO.MemoryStream();
// Add a handler which will be notified on progress changes.
// It will notify on each chunk download and when the
// download is completed or failed.
request.MediaDownloader.ProgressChanged +=
        (IDownloadProgress progress) =>
        case DownloadStatus.Downloading:
        case DownloadStatus.Completed:
            Console.WriteLine("Download complete.");
        case DownloadStatus.Failed:
            Console.WriteLine("Download failed.");


file_id = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo'
content = drive_service.export_file(file_id,


var fileId = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo';
var dest = fs.createWriteStream('/tmp/resume.pdf');
   fileId: fileId,
   mimeType: 'application/pdf'
.on('end', function() {
.on('error', function(err) {
  console.log('Error during download', err);

Apps should display converted files as read-only, or let users save them as new files.

Open and upload files using the Google Picker API

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:

Select a file from a picker window.

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="">
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google Picker Example</title>

    <script type="text/javascript">

    // The Browser API key obtained from the Google API Console.
    // Replace with your own Browser API key, or your own key.
    var developerKey = 'xxxxxxxYYYYYYYY-12345678';

    // The Client ID obtained from the Google API Console. Replace with your own Client ID.
    var clientId = ""

    // Replace with your own App ID. (Its the first number in your Client ID)
    var appId = "1234567890";

    // Scope to use to access user's Drive items.
    var scope = [''];

    var pickerApiLoaded = false;
    var oauthToken;

    // Use the Google API Loader script to load the google.picker script.
    function loadPicker() {
      gapi.load('auth', {'callback': onAuthApiLoad});
      gapi.load('picker', {'callback': onPickerApiLoad});

    function onAuthApiLoad() {
            'client_id': clientId,
            'scope': scope,
            'immediate': false

    function onPickerApiLoad() {
      pickerApiLoaded = true;

    function handleAuthResult(authResult) {
      if (authResult && !authResult.error) {
        oauthToken = authResult.access_token;

    // Create and render a Picker object for searching images.
    function createPicker() {
      if (pickerApiLoaded && oauthToken) {
        var view = new google.picker.View(google.picker.ViewId.DOCS);
        var picker = new google.picker.PickerBuilder()
            .addView(new google.picker.DocsUploadView())

    // A simple callback implementation.
    function pickerCallback(data) {
      if (data.action == google.picker.Action.PICKED) {
        var fileId =[0].id;
        alert('The user selected: ' + fileId);
    <div id="result"></div>

    <!-- The Google API Loader script. -->
    <script type="text/javascript" src=""></script>

The AppId set here and the client ID used for authorizing access to a user's files must be contained in the same app. Within the API Console, AppId can be identified as the "Project Number" on the Project Dashboard, or as the first number in the client ID.

Important:The setOAuthToken function allows an app to use the current auth token to determine which Google account the picker uses to display the files. If a user is signed into multiple Google accounts, this allows the picker to display the files of the appropriate authorized account.

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.

Send feedback about...