Google Drive SDK

Download Files

The Drive API allows you to download files that are stored in Google Drive. Also, you can download Google Documents (Documents, Spreadsheets, Presentations, etc.) and export them to formats that your app can handle. Drive also supports providing users direct access to a file via a link.

To download files, you'll need to make two authorized HTTP GET requests:

  1. First, retrieve the appropriate download URL provided in the file's metadata.
  2. Then, retrieve the actual file content (or link) using the download URL.

Depending on the type of download you'd like to perform — a file, a Google Document, or a content link — you'll use one of the following URLs:

  • Download a file — downloadURL
  • Download and export a Google Doc — exportLinks
  • Link a user to a file — webContentLink

The rest of this page provides detailed instructions for performing these types of downloads:

Downloading a file

Download a file by retrieving its download URL and the retrieving the file itself. To find the download URL, fetch a file's metadata with the files.get or the files.list methods. The response contains the link in the downloadUrl field. For example:

{
 "kind": "drive#file",
 "id": "0B0iTh2ZTRkNjI1ZjUtOGIwZS00YzhiLWJmMWMtNWI4YzY3NzQyNWQ2",
 "downloadUrl": "https://doc-04-c1-docs.googleusercontent.com/docs/securesc/ivearmirmg66&e=download&gd=true",
 ...
}

Once you have fetched the URL, you can use it to download the file content by making an authorized GET request to it. For example:

GET https://doc-04-c1-docs.googleusercontent.com/docs/securesc/ivearmirmg66&e=download&gd=true
Authorization: Bearer ya29.AHESVbXTUv5mHMo3RYfmS1YJonjzzdTOFZwvyOAUVhrs

Examples

Here are examples of performing a file download with our Drive API client libraries.

Java

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;

import java.io.IOException;
import java.io.InputStream;

// ...

public class MyClass {

  // ...

  /**
   * Download a file's content.
   * 
   * @param service Drive API service instance.
   * @param file Drive File instance.
   * @return InputStream containing the file's content if successful,
   *         {@code null} otherwise.
   */
  private static InputStream downloadFile(Drive service, File file) {
    if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
      try {
        HttpResponse resp =
            service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl()))
                .execute();
        return resp.getContent();
      } catch (IOException e) {
        // An error occurred.
        e.printStackTrace();
        return null;
      }
    } else {
      // The file doesn't have any content stored on Drive.
      return null;
    }
  }

  // ...
}

.NET

using Google.Apis.Authentication;
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;

using System.Net;
// ...

public class MyClass {

  // ...

  /// <summary>
  /// Download a file and return a string with its content.
  /// </summary>
  /// <param name="authenticator">
  /// Authenticator responsible for creating authorized web requests.
  /// </param>
  /// <param name="file">Drive File instance.</param>
  /// <returns>File's content if successful, null otherwise.</returns>
  public static System.IO.Stream DownloadFile(
      IAuthenticator authenticator, File file) {
    if (!String.IsNullOrEmpty(file.DownloadUrl)) {
      try {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
            new Uri(file.DownloadUrl));
        authenticator.ApplyAuthenticationToRequest(request);
        HttpWebResponse response = (HttpWebResponse) request.GetResponse();
        if (response.StatusCode == HttpStatusCode.OK) {
          return response.GetResponseStream();
        } else {
          Console.WriteLine(
              "An error occurred: " + response.StatusDescription);
          return null;
        }
      } catch (Exception e) {
        Console.WriteLine("An error occurred: " + e.Message);
        return null;
      }
    } else {
      // The file doesn't have any content stored on Drive.
      return null;
    }
  }

  //...

}

PHP

/**
 * Download a file's content.
 *
 * @param Google_DriveService $service Drive API service instance.
 * @param File $file Drive File instance.
 * @return String The file's content if successful, null otherwise.
 */
function downloadFile($service, $file) {
  $downloadUrl = $file->getDownloadUrl();
  if ($downloadUrl) {
    $request = new Google_HttpRequest($downloadUrl, 'GET', null, null);
    $httpRequest = Google_Client::$io->authenticatedRequest($request);
    if ($httpRequest->getResponseHttpCode() == 200) {
      return $httpRequest->getResponseBody();
    } else {
      // An error occurred.
      return null;
    }
  } else {
    // The file doesn't have any content stored on Drive.
    return null;
  }
}

Python

from apiclient import errors
# ...

def download_file(service, drive_file):
  """Download a file's content.

  Args:
    service: Drive API service instance.
    drive_file: Drive File instance.

  Returns:
    File's content if successful, None otherwise.
  """
  download_url = drive_file.get('downloadUrl')
  if download_url:
    resp, content = service._http.request(download_url)
    if resp.status == 200:
      print 'Status: %s' % resp
      return content
    else:
      print 'An error occurred: %s' % resp
      return None
  else:
    # The file doesn't have any content stored on Drive.
    return None

Ruby

##
# Download a file's content
#
# @param [Google::APIClient] client
#   Authorized client instance
# @param [Google::APIClient::Schema::Drive::V2::File]
#   Drive File instance
# @return 
#   File's content if successful, nil otherwise
def download_file(client, file)
  if file.download_url
    result = client.execute(:uri => file.download_url)
    if result.status == 200
      return result.body
    else
      puts "An error occurred: #{result.data['error']['message']}"
      return nil
  else
    # The file doesn't have any content stored on Drive.
    return nil
  end
end

JavaScript

/**
 * Download a file's content.
 *
 * @param {File} file Drive File instance.
 * @param {Function} callback Function to call when the request is complete.
 */
function downloadFile(file, callback) {
  if (file.downloadUrl) {
    var accessToken = gapi.auth.getToken().access_token;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file.downloadUrl);
    xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
    xhr.onload = function() {
      callback(xhr.responseText);
    };
    xhr.onerror = function() {
      callback(null);
    };
    xhr.send();
  } else {
    callback(null);
  }
}

Go

import (
  "code.google.com/p/google-api-go-client/drive/v2"
  "fmt"
  "net/http"
  "io/ioutil"
)
// DownloadFile downloads the content of a given file object
func DownloadFile(d *drive.Service, t http.RoundTripper, f *drive.File) (string, error) {
  // t parameter should use an oauth.Transport
  downloadUrl := f.DownloadUrl
  if downloadUrl == "" {
    // If there is no downloadUrl, there is no body
    fmt.Printf("An error occurred: File is not downloadable")
    return "", nil
  }
  req, err := http.NewRequest("GET", downloadUrl, nil)
  if err != nil {
    fmt.Printf("An error occurred: %v\n", err)
    return "", err
  }
  resp, err := t.RoundTrip(req)
  // Make sure we close the Body later
  defer resp.Body.Close()
  if err != nil {
    fmt.Printf("An error occurred: %v\n", err)
    return "", err
  }
  body, err := ioutil.ReadAll(resp.Body)
  if err != nil {
    fmt.Printf("An error occurred: %v\n", err)
    return "", err
  }
  return string(body), nil
}

Partial download

Partial download involves downloading only a specified portion of a file. You can specify the portion of the file you want to dowload by using a byte range with the Range header. For example:

Range: bytes=500-999

Downloading Google Documents

The file resource includes exportLinks URLs for the various export formats for Google Documents (Documents, Spreadsheets, Presentations, etc.). Use these URLs in the same way as the downloadURL. The following examples demonstrate how to download a Google Document in PDF format using the client libraries:

Java

String downloadUrl = file.getExportLinks().get("application/pdf");

.NET

String downloadUrl = file.ExportLinks["application/pdf"];

PHP

downloadUrl = file->getExportLinks()['application/pdf'];

Python

download_url = file['exportLinks']['application/pdf']

Ruby

download_url = file['exportLinks']['application/pdf']

JavaScript

download_url = file['exportLinks']['application/pdf'];

Go

download_url := file.ExportLinks["application/pdf"]

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
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, PDF application/pdf

Downloading files in a browser

If you want to allow an unauthorized user to download a file directly in a web browser instead of through the API, use the webContentLink. You can either redirect a user to this URL, or offer it as a clickable link.

Java

String downloadUrl = file.getWebContentLink();

.NET

String downloadUrl = file.WebContentLink;

PHP

downloadUrl = file->getWebContentLink();

Python

download_url = file['webContentLink']

Ruby

download_url = file['webContentLink']

JavaScript

download_url = file['webContentLink'];

Go

download_url := file.ExportLinks["application/pdf"]

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.