Download files

The Drive API supports three types of downloads:

  • Downloads of files stored in Google Drive.
  • Downloads of exported versions of G Suite files (Google Docs, Sheets, Slides, and so on) in formats that your app can handle.
  • Downloads of a file using the URL in the webContentLink property.

The rest of this guide provides detailed instructions for performing these types of downloads.

Download a file stored on Google Drive

To download a file stored on Google Drive, use the files.get method with the ID of the file to download and the alt=media URL parameter. The alt=media URL parameter tells the server that a download of content is being requested.

The following code snippet shows how to download a file with the Drive API client libraries.

Java

String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().get(fileId)
    .executeMediaAndDownloadTo(outputStream);

Python

file_id = '0BwwA4oUTeiV1UVNwOHItT0xfa2M'
request = drive_service.files().get_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)

PHP

$fileId = '0BwwA4oUTeiV1UVNwOHItT0xfa2M';
$response = $driveService->files->get($fileId, array(
    'alt' => 'media'));
$content = $response->getBody()->getContents();

.NET

var fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M";
var request = driveService.Files.Get(fileId);
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 = '0BwwA4oUTeiV1UVNwOHItT0xfa2M'
content = drive_service.get_file(file_id, download_dest: StringIO.new)

Node.js

var fileId = '0BwwA4oUTeiV1UVNwOHItT0xfa2M';
var dest = fs.createWriteStream('/tmp/photo.jpg');
drive.files.get({
  fileId: fileId,
  alt: 'media'
})
    .on('end', function () {
      console.log('Done');
    })
    .on('error', function (err) {
      console.log('Error during download', err);
    })
    .pipe(dest);

This snippet uses the executeMediaAndDownloadTo() method which adds the alt=media URL parameter to the underlying HTTP request.

File downloads initiated from your app require at least read access to the file. Your app must be authorized with a scope that allows file content read access. 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 labels.restricted field to false. To learn more about scopes, refer to Authenticate your users.

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.

Partial download

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

Range: bytes=500-999

Download a Google Document

Download G Suite documents using the files.export method. Exports use the same alt=media approach as downloading other content in Drive.

The following examples demonstrate how to download a Google Document in PDF format using the client libraries:

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);

The snippet declares the MIME type for export as application/pdf. For a a complete list of all MIME types supported for each G Suite document, refer to G Suite documents and corresponding export MIME types

Viewing files in a browser

If you want to allow a user to view 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. The file must be either owned by or shared with the user in order to view it.