Dateien herunterladen und exportieren

Die Google Drive API unterstützt verschiedene Arten von Download- und Exportaktionen, wie in der folgenden Tabelle aufgeführt:

Downloads
Inhalt der Blob-Datei mit der Methode files.get und dem URL-Parameter alt=media.
Blob-Dateiinhalt in einer früheren Version mithilfe der Methode revisions.get mit dem URL-Parameter alt=media.
Blob-Dateiinhalt in einem Browser mithilfe des Felds webContentLink.
Exporte
Google Workspace-Dokumentinhalte in einem Format, das Ihre App mit files.export verarbeiten kann.
Google Workspace-Dokumentinhalte in einem Browser über das Feld exportLinks.
Inhalte von Google Workspace-Dokumenten in einer früheren Version eines Browsers über das Feld exportLinks.

Im weiteren Verlauf dieses Leitfadens finden Sie eine ausführliche Anleitung für diese Download- und Exportaktionen.

Inhalt der Blob-Datei herunterladen

Wenn Sie eine in Drive gespeicherte Blob-Datei herunterladen möchten, verwenden Sie die Methode files.get mit der ID der heruntergeladenen Datei und den URL-Parameter alt=media. Mit dem URL-Parameter alt=media wird dem Server mitgeteilt, dass ein Download von Inhalten als alternatives Antwortformat angefordert wird.

Der URL-Parameter alt=media ist ein Systemparameter, der in allen Google REST APIs verfügbar ist. Wenn Sie eine Clientbibliothek für die Drive API verwenden, müssen Sie diesen Parameter nicht explizit festlegen.

Im folgenden Codebeispiel wird gezeigt, wie Sie mit der Methode files.get eine Datei mit den Drive API-Clientbibliotheken herunterladen.

Java

drive/snippets/drive_v3/src/main/java/DownloadFile.java
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;

/* Class to demonstrate use-case of drive's download file. */
public class DownloadFile {

  /**
   * Download a Document file in PDF format.
   *
   * @param realFileId file ID of any workspace document format file.
   * @return byte array stream if successful, {@code null} otherwise.
   * @throws IOException if service account credentials file not found.
   */
  public static ByteArrayOutputStream downloadFile(String realFileId) throws IOException {
        /* Load pre-authorized user credentials from the environment.
           TODO(developer) - See https://developers.google.com/identity for
          guides on implementing OAuth2 for your application.*/
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Build a new authorized API client service.
    Drive service = new Drive.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Drive samples")
        .build();

    try {
      OutputStream outputStream = new ByteArrayOutputStream();

      service.files().get(realFileId)
          .executeMediaAndDownloadTo(outputStream);

      return (ByteArrayOutputStream) outputStream;
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      System.err.println("Unable to move file: " + e.getDetails());
      throw e;
    }
  }
}

Python

drive/snippets/drive-v3/file_snippet/download_file.py?
from __future__ import print_function

import io

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaIoBaseDownload


def download_file(real_file_id):
    """Downloads a file
    Args:
        real_file_id: ID of the file to download
    Returns : IO object with location.

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_id = real_file_id

        # pylint: disable=maybe-no-member
        request = service.files().get_media(fileId=file_id)
        file = io.BytesIO()
        downloader = MediaIoBaseDownload(file, request)
        done = False
        while done is False:
            status, done = downloader.next_chunk()
            print(F'Download {int(status.progress() * 100)}.')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.getvalue()


if __name__ == '__main__':
    download_file(real_file_id='1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9')

Node.js

drive/snippets/drive_v3/file_snippets/download_file.js
/**
 * Downloads a file
 * @param{string} realFileId file ID
 * @return{obj} file status
 * */
async function downloadFile(realFileId) {
  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app

  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});

  fileId = realFileId;
  try {
    const file = await service.files.get({
      fileId: fileId,
      alt: 'media',
    });
    console.log(file.status);
    return file.status;
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}

PHP

drive/snippets/drive_v3/src/DriveDownloadFile.php
use Google\Client;
use Google\Service\Drive;
function downloadFile()
 {
    try {

      $client = new Client();
      $client->useApplicationDefaultCredentials();
      $client->addScope(Drive::DRIVE);
      $driveService = new Drive($client);
      $realFileId = readline("Enter File Id: ");
      $fileId = '0BwwA4oUTeiV1UVNwOHItT0xfa2M';
      $fileId = $realFileId;
      $response = $driveService->files->get($fileId, array(
          'alt' => 'media'));
      $content = $response->getBody()->getContents();
      return $content;

    } catch(Exception $e) {
      echo "Error Message: ".$e;
    }

}

.NET

drive/snippets/drive_v3/DriveV3Snippets/DownloadFile.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Download;
using Google.Apis.Drive.v3;
using Google.Apis.Services;

namespace DriveV3Snippets
{
    // Class to demonstrate use-case of drive's download file.
    public class DownloadFile
    {
        /// <summary>
        /// Download a Document file in PDF format.
        /// </summary>
        /// <param name="fileId">file ID of any workspace document format file.</param>
        /// <returns>byte array stream if successful, null otherwise.</returns>
        public static MemoryStream DriveDownloadFile(string fileId)
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for 
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential
                    .GetApplicationDefault()
                    .CreateScoped(DriveService.Scope.Drive);

                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Snippets"
                });

                var request = service.Files.Get(fileId);
                var stream = new 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 +=
                    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);

                return stream;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}

Dieses Codebeispiel verwendet eine Bibliotheksmethode, die den URL-Parameter alt=media der zugrunde liegenden HTTP-Anfrage hinzufügt.

Von Ihrer Anwendung gestartete Dateidownloads müssen mit einem Bereich autorisiert werden, der Lesezugriff auf den Dateiinhalt zulässt. Beispielsweise ist eine App mit dem Bereich drive.readonly.metadata nicht berechtigt, den Dateiinhalt herunterzuladen. In diesem Codebeispiel wird der eingeschränkte Drive-Dateibereich verwendet, mit dem Nutzer alle Ihre Drive-Dateien ansehen und verwalten können. Weitere Informationen zu Drive-Umfängen finden Sie unter API-spezifische Autorisierungs- und Authentifizierungsinformationen.

Nutzer mit Bearbeitungsberechtigungen können den Download einschränken, indem sie schreibgeschützte Nutzer festlegen. Dazu setzen Sie das Feld copyRequiresWriterPermission auf false.

Dateien, die als Missbrauch eingestuft werden (z. B. Schadsoftware), können nur vom Dateieigentümer heruntergeladen werden. Außerdem muss der get-Abfrageparameter acknowledgeAbuse=true angegeben werden, um anzugeben, dass der Nutzer das Risiko des Herunterladens potenziell unerwünschter Software oder anderer missbräuchlicher Dateien bestätigt hat. Ihre Anwendung sollte den Nutzer interaktiv warnen, bevor dieser Abfrageparameter verwendet wird.

Teilweiser Download

Beim teilweisen Download wird nur ein bestimmter Teil einer Datei heruntergeladen. Sie können den Teil der Datei, den Sie herunterladen möchten, mit einem Bytebereich mit dem Header Range angeben. Beispiel:

Range: bytes=500-999

Inhalt einer Blob-Datei in einer früheren Version herunterladen

Verwenden Sie die Methode revisions.get mit der ID der herunterzuladenden Datei, die ID der Überarbeitung und den URL-Parameter alt=media, um den Inhalt von Blob-Dateien in einer früheren Version herunterzuladen. Mit dem URL-Parameter alt=media wird dem Server mitgeteilt, dass ein Download von Inhalten als alternatives Antwortformat angefordert wird. Ähnlich wie files.get akzeptiert die Methode revisions.get auch den optionalen Abfrageparameter acknowledgeAbuse und den Header Range. Weitere Informationen zum Herunterladen von Überarbeitungen finden Sie unter Überarbeitungen herunterladen und veröffentlichen.

Inhalt von Blob-Dateien in einem Browser herunterladen

Wenn Sie den Inhalt von Blob-Dateien herunterladen möchten, die in Drive in einem Browser und nicht über die API gespeichert sind, verwenden Sie das Feld webContentLink der Ressource Files. Wenn der Nutzer Zugriff auf die Datei hat, wird ein Link zum Herunterladen der Datei und dem Inhalt zurückgegeben. Sie können Nutzer entweder zu dieser URL weiterleiten oder sie als anklickbaren Link anbieten.

Google Workspace-Dokumentinhalte exportieren

Verwenden Sie die files.export-Methode mit der ID der zu exportierenden Datei und dem richtigen MIME-Typ, um Google Workspace-Dokumentbyte zu exportieren. Exportierte Inhalte sind auf 10 MB begrenzt.

Im folgenden Codebeispiel wird gezeigt, wie Sie mit der Methode files.export ein Google Workspace-Dokument im PDF-Format mithilfe der Drive API-Clientbibliotheken exportieren:

Java

drive/snippets/drive_v3/src/main/java/ExportPdf.java
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;

/* Class to demonstrate use-case of drive's export pdf. */
public class ExportPdf {

  /**
   * Download a Document file in PDF format.
   *
   * @param realFileId file ID of any workspace document format file.
   * @return byte array stream if successful, {@code null} otherwise.
   * @throws IOException if service account credentials file not found.
   */
  public static ByteArrayOutputStream exportPdf(String realFileId) throws IOException {
    // Load pre-authorized user credentials from the environment.
    // TODO(developer) - See https://developers.google.com/identity for
    // guides on implementing OAuth2 for your application.
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Build a new authorized API client service.
    Drive service = new Drive.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Drive samples")
        .build();

    OutputStream outputStream = new ByteArrayOutputStream();
    try {
      service.files().export(realFileId, "application/pdf")
          .executeMediaAndDownloadTo(outputStream);

      return (ByteArrayOutputStream) outputStream;
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      System.err.println("Unable to export file: " + e.getDetails());
      throw e;
    }
  }
}

Python

drive/snippets/drive-v3/file_snippet/export_pdf.py
from __future__ import print_function

import io

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaIoBaseDownload


def export_pdf(real_file_id):
    """Download a Document file in PDF format.
    Args:
        real_file_id : file ID of any workspace document format file
    Returns : IO object with location

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_id = real_file_id

        # pylint: disable=maybe-no-member
        request = service.files().export_media(fileId=file_id,
                                               mimeType='application/pdf')
        file = io.BytesIO()
        downloader = MediaIoBaseDownload(file, request)
        done = False
        while done is False:
            status, done = downloader.next_chunk()
            print(F'Download {int(status.progress() * 100)}.')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.getvalue()


if __name__ == '__main__':
    export_pdf(real_file_id='1zbp8wAyuImX91Jt9mI-CAX_1TqkBLDEDcr2WeXBbKUY')

Node.js

drive/snippets/drive_v3/file_snippets/export_pdf.js
/**
 * Download a Document file in PDF format
 * @param{string} fileId file ID
 * @return{obj} file status
 * */
async function exportPdf(fileId) {
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});

  try {
    const result = await service.files.export({
      fileId: fileId,
      mimeType: 'application/pdf',
    });
    console.log(result.status);
    return result;
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}

PHP

drive/snippets/drive_v3/src/DriveExportPdf.php
use Google\Client;
use Google\Service\Drive;
function exportPdf()
{
    try {
        $client = new Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);
        $realFileId = readline("Enter File Id: ");
        $fileId = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo';
        $fileId = $realFileId;
        $response = $driveService->files->export($fileId, 'application/pdf', array(
            'alt' => 'media'));
        $content = $response->getBody()->getContents();
        return $content;

    }  catch(Exception $e) {
         echo "Error Message: ".$e;
    }

}

.NET

drive/snippets/drive_v3/DriveV3Snippets/ExportPdf.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Download;
using Google.Apis.Drive.v3;
using Google.Apis.Services;

namespace DriveV3Snippets
{
    // Class to demonstrate use of Drive export pdf
    public class ExportPdf
    {
        /// <summary>
        /// Download a Document file in PDF format.
        /// </summary>
        /// <param name="fileId">Id of the file.</param>
        /// <returns>Byte array stream if successful, null otherwise</returns>
        public static MemoryStream DriveExportPdf(string fileId)
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for 
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                    .CreateScoped(DriveService.Scope.Drive);

                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Snippets"
                });

                var request = service.Files.Export(fileId, "application/pdf");
                var stream = new 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 +=
                    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);
                return stream;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}

In diesem Codebeispiel wird der eingeschränkte Bereich drive verwendet, mit dem Nutzer alle Ihre Drive-Dateien ansehen und verwalten können. Weitere Informationen zu Drive-Umfängen finden Sie unter API-spezifische Autorisierungs- und Authentifizierungsinformationen.

Im Codebeispiel wird der Export-MIME-Typ auch als application/pdf deklariert. Eine vollständige Liste aller MIME-Typen, die für jedes Google Workspace-Dokument unterstützt werden, finden Sie in diesem Artikel.

Google Workspace-Dokumentinhalte in einem Browser exportieren

Wenn Sie Google Workspace-Dokumentinhalte in einem Browser exportieren möchten, verwenden Sie das Feld exportLinks der Files-Ressource. Je nach Dokumenttyp wird für jeden verfügbaren MIME-Typ ein Link zum Herunterladen der Datei und des Inhalts zurückgegeben. Sie können einen Nutzer entweder zu einer URL weiterleiten oder ihn als anklickbaren Link anbieten.

Inhalte von Google Workspace-Dokumenten aus einer früheren Version in einem Browser exportieren

Wenn Sie Google Workspace-Dokumentinhalte in einer früheren Version in einem Browser exportieren möchten, verwenden Sie die Methode revisions.get mit der ID der herunterzuladenden Datei und der ID der Überarbeitung. Wenn der Nutzer Zugriff auf die Datei hat, wird ein Link zum Herunterladen der Datei und deren Inhalt zurückgegeben. Sie können Nutzer entweder zu dieser URL weiterleiten oder sie als anklickbaren Link anbieten.