Hide
Drive REST API

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.

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:

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

Downloading a file

Preferred method: using alt=media

To download files, you make an authorized HTTP GET request to the file's resource URL and include the query parameter alt=media. For example:

GET https://www.googleapis.com/drive/v2/files/0B9jNhSvVjoIVM3dKcGRKRmVIOVU?alt=media
Authorization: Bearer ya29.AHESVbXTUv5mHMo3RYfmS1YJonjzzdTOFZwvyOAUVhrs

Downloading the file requires the user to have at least read access. Additionally, your app must be authorized with a scope that allows reading of file content. For example, an app using the drive.readonly.metadata scope would not be authorized to download the file contents. Users with edit permission may restrict downloading by read-only users by setting the restricted label to true.

Files identified as abusive (malware, etc.) are only downloadable by the owner. Additionally, the query parameter acknowledgeAbuse=true must be included to indicate that the user has acknowledged the risk of downloading potential malware. Your application should interactively warn the user before using this query parameter.

Compared to downloading with downloadUrl (described below), alt=media offers the advantage of predicable, long-lived, client-constructable download URLs.

Alternate method: using downloadUrl

To download files this way, you 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.

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

The downloadUrl field is a short-lived value and is typically only good for 8 hours. For this reason, it's usually necessary to issue both requests around the same time. The downloadUrl is not predictable by the client and must be fetched from the server metadata.

Examples

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

Java

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 {
        // uses alt=media query parameter to request content
        return service.files().get(file.getId()).executeMediaAsInputStream();
      } 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_Servie_Drive $service Drive API service instance.
 * @param Google_Servie_Drive_DriveFile $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_Http_Request($downloadUrl, 'GET', null, null);
    $httpRequest = $service->getClient()->getAuth()->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
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/vnd.google-apps.script+json

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