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"],
  "action":"open",
  "userId":"103354693083460731603"
}

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
HTML (zipped) application/zip
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
EPUB application/epub+zip
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
TSV (first sheet only) text/tab-separated-values
HTML (zipped) application/zip
Drawings JPEG image/jpeg
PNG image/png
SVG image/svg+xml
PDF application/pdf
Presentations MS PowerPoint application/vnd.openxmlformats-officedocument.presentationml.presentation
Open Office presentation application/vnd.oasis.opendocument.presentation
PDF application/pdf
Plain text text/plain
Apps Scripts JSON application/vnd.google-apps.script+json

The about resource contains additional information about available export formats for each file type.

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.

Java

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

Python

file_id = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo'
request = drive_service.files().export_media(fileId=file_id,
                                             mimeType='application/pdf')
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)

PHP

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

.NET

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) =>
{
    switch (progress.Status)
    {
        case DownloadStatus.Downloading:
            {
                Console.WriteLine(progress.BytesDownloaded);
                break;
            }
        case DownloadStatus.Completed:
            {
                Console.WriteLine("Download complete.");
                break;
            }
        case DownloadStatus.Failed:
            {
                Console.WriteLine("Download failed.");
                break;
            }
    }
};
request.Download(stream);

Ruby

file_id = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo'
content = drive_service.export_file(file_id,
                                    'application/pdf',
                                    download_dest: StringIO.new)

Node.js

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

Objective-C

NSString *fileId = @"1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo";

GTLRDriveQuery_FilesExport *query = [GTLRDriveQuery_FilesExport queryForMediaWithFileId:fileId
                                                                               mimeType:@"application/pdf"];
[driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
                                                     GTLRDataObject *file,
                                                     NSError *error) {
    if (error == nil) {
        NSLog(@"Downloaded %lu bytes", (unsigned long)file.data.length);
    } else {
        NSLog(@"An error occurred: %@", error);
    }
}];

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

Using the file picker

In addition to launching an application from Drive, applications can display a file picker to select content from within the app itself. See the files picker guide for additional details.

Send feedback about...

Drive REST API
Drive REST API