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

使用者選取檔案並按一下雲端硬碟 UI 的「開啟方式」選單項目時,雲端硬碟會將使用者重新導向至設定雲端硬碟 UI 整合作業中定義的該應用程式「開啟」網址。

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

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

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

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

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

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

如「設定雲端硬碟 UI 整合」一文所述,您的應用程式會收到範本變數,其中包含用於開啟檔案的資訊。您的應用程式會在 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
    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 雲端硬碟 UI 開啟應用程式之外,應用程式也可以顯示檔案選擇器,以在應用程式中選取內容。詳情請參閱「Google Picker」。