與雲端硬碟使用者介面整合's "開啟內容選單

使用者選取檔案並點選 Google 雲端硬碟 UI 的「開啟方式」選單項目後,Google 雲端硬碟會將使用者重新導向至該應用程式的「開啟」網址,該網址定義於「設定 Google 雲端硬碟 UI 整合」。

如果您在設定雲端硬碟 UI 整合時勾選「匯入」方塊,使用者可以選取應用程式專屬和 Google Workspace 檔案的組合來開啟。設定雲端硬碟 UI 整合時,應用程式專屬檔案會定義在「預設 MIME 類型」和「預設副檔名」欄位中,而 Google Workspace 檔案則定義在「次要 MIME 類型」和「次要副檔名」欄位中。

針對使用者要開啟的每個檔案,雲端硬碟會根據您定義的預設和次要 MIME 類型檢查 MIME 類型:

  • 對於「預設 MIME 類型」欄位中定義的 MIME 類型,系統會將檔案 ID 傳遞至您的應用程式。如要瞭解如何處理應用程式專屬檔案,請參閱「處理應用程式專屬文件的開啟網址」。

  • 如果「次要 MIME 類型」欄位中定義了 MIME 類型,雲端硬碟 UI 會顯示對話方塊,詢問使用者要將 Google Workspace 檔案轉換為哪種檔案類型。舉例來說,如果您在雲端硬碟使用者介面中選取 Google 文件檔案,且「次要 MIME 類型」欄位顯示您的應用程式支援 text/plain 或 application/pdf,雲端硬碟使用者介面會詢問使用者是否要轉換為純文字或 PDF。

    如要瞭解如何處理 Google Workspace 檔案,請參閱「處理 Google Workspace 文件的開啟網址」。如要查看 Google Workspace 文件和 MIME 類型轉換格式的清單,請參閱「匯出 Google Workspace 文件的 MIME 類型」。

處理應用程式專屬文件的「開啟網址」

如「設定 Google 雲端硬碟使用者介面整合」一文所述,應用程式會收到範本變數,其中包含應用程式開啟檔案所需的資訊。應用程式會在 state 參數中收到一組預設的範本變數。應用程式專屬「開啟網址」的預設 state 資訊如下:

{
  "ids": ["ID"],
  "resourceKeys":{"RESOURCE_KEYS":"RESOURCE_KEYS"},
  "action":"open",
  "userId":"USER_ID"
}

這項輸出內容包含下列值:

  • ID:父項資料夾的 ID。
  • RESOURCE_KEYS:檔案 ID 的 JSON 字典,對應至各自的資源鍵。
  • open:正在執行的動作。使用開啟網址時,值為 open
  • USER_ID:可專屬識別使用者的設定檔 ID。

應用程式必須按照下列步驟處理這項要求:

  1. 確認 action 欄位的值為 open,且 ids 欄位存在。
  2. 使用 userId 值為使用者建立新工作階段。如要進一步瞭解已登入的使用者,請參閱「使用者和新事件」。
  3. 使用 files.get 方法檢查權限、擷取檔案中繼資料,並使用 ID 值下載檔案內容。
  4. 如果要求中已設定 resourceKeys,請設定 X-Goog-Drive-Resource-Keys 要求標頭。如要進一步瞭解資源金鑰,請參閱「使用資源金鑰存取透過連結共用的檔案」。

state 參數經過網址編碼,因此應用程式必須處理逸出字元,並將其剖析為 JSON。

處理 Google Workspace 文件的「開啟網址」

如「設定雲端硬碟 UI 整合」一文所述,應用程式會在 state 參數中收到一組預設的範本變數。Google Workspace 開啟網址的預設 state資訊如下:

{
  "exportIds": ["ID"],
  "resourceKeys":{"RESOURCE_KEYS":"RESOURCE_KEYS"},
  "action":"open",
  "userId":"USER_ID"
}

這項輸出內容包含下列值:

  • EXPORT_ID:以半形逗號分隔的匯出檔案 ID 清單 (僅在開啟內建 Google 文件時使用)。
  • RESOURCE_KEYS:檔案 ID 的 JSON 字典,對應至各自的資源鍵。
  • open:正在執行的動作。使用開啟網址時,值為 open
  • USER_ID:用於識別使用者的設定檔 ID。

應用程式必須按照下列步驟處理這項要求:

  1. 偵測 state 欄位中的 open 值和 exportIds 欄位,確認這是開啟檔案的要求。

  2. 使用 files.get 方法檢查權限、擷取檔案中繼資料,並使用 EXPORT_ID 值判斷 MIME 類型。

  3. 使用 files.export 方法轉換檔案內容。下列程式碼範例說明如何將 Google Workspace 文件匯出為要求的 MIME 類型。

  4. 如果要求中已設定 resourceKey,請設定 X-Goog-Drive-Resource-Keys 要求標頭。如要進一步瞭解資源金鑰,請參閱「使用資源金鑰存取透過連結共用的檔案」。

    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
    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
    <?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;
        }
    
    }

以唯讀模式顯示轉換後的檔案,或顯示對話方塊,讓使用者將檔案儲存為新檔案類型。

state 參數經過網址編碼,因此應用程式必須處理逸出字元,並將其剖析為 JSON。

使用者和新事件

雲端硬碟應用程式應將所有「開啟方式」事件視為潛在登入事件。部分使用者可能有多個帳戶,因此 state 參數中的使用者 ID 可能與目前的工作階段不符。如果 state 參數中的使用者 ID 與目前工作階段不符,請結束應用程式的目前工作階段,並以要求的使用者身分登入。

除了透過 Google 雲端硬碟使用者介面開啟應用程式,應用程式也可以顯示檔案選擇器,讓使用者從應用程式中選取內容。詳情請參閱 Google Picker