Drive UI의 '다음으로 열기' 컨텍스트 메뉴와 통합

사용자가 파일을 선택하고 Drive UI의 '연결 프로그램'을 클릭할 때 메뉴 항목, Drive 리디렉션 사용자에게 Drive UI 구성에 정의된 앱의 URL 열기'를 통합에 대해 자세히 알아보세요.

'가져오기' 체크박스를 선택한 경우 메시지가 표시됩니다. 통합의 경우 사용자는 앱별 및 열려는 Google Workspace 파일입니다. Drive UI를 구성하는 경우 통합 시 앱별 파일은 '기본 MIME 유형'에 정의되어 있음 및 '기본 파일 확장자' 필드를 사용하는 반면 Google Workspace에서는 파일은 "보조 MIME 유형"에 정의되어 있습니다. '보조 파일 확장자'입니다 있습니다.

사용자가 열려는 각 파일에 대해 Drive는 MIME를 확인합니다. 정의된 기본 및 보조 MIME 유형과 비교하여 다음과 같습니다.

  • '기본 MIME 유형'에 정의된 MIME 유형 필드에서 파일 ID는 앱에 전달됩니다. 앱별 파일 처리 방법에 관한 자세한 내용은 앱별 문서의 열기 URL 처리를 참고하세요.

  • '보조 MIME 유형'에 정의된 MIME 유형 필드에서 Drive UI에 사용자에게 파일 형식을 묻는 대화상자가 표시됨 Google Workspace 파일을 예를 들어 Drive UI의 Google Docs 파일 및 'Secondary MIME 유형' 필드가 텍스트/일반 또는 애플리케이션/pdf를 지원함을 나타내는 경우 사용자에게 일반 텍스트로 변환할지 묻는 Drive UI 또는 PDF.

    Google Workspace 처리 방법에 관한 자세한 내용은 파일에 대한 자세한 내용은 Google Workspace 문서의 공개 URL 처리를 참고하세요. Google Workspace 문서 및 MIME 유형 변환 형식의 목록은 다음과 같습니다. 참고: Google Workspace용 MIME 유형 내보내기 문서를 참조하세요.

앱별 문서의 URL 열기 처리

Drive UI 구성 통합, 앱이 열릴 정보가 포함된 템플릿 변수를 수신합니다. 있습니다. 앱에서 기본 템플릿 변수 집합을 수신합니다. (state 매개변수 내) 이 앱별 Open URL의 기본 state 정보는 다음과 같습니다.

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

이 출력에는 다음 값이 포함됩니다.

  • ID: 상위 폴더의 ID입니다.
  • RESOURCE_KEYS: 매핑된 파일 ID의 JSON 사전 해당 리소스 키를 줄일 수 있습니다
  • open: 수행 중인 동작입니다. Open()을 사용하는 경우 값은 open입니다. URL입니다.
  • USER_ID: 사용자를 고유하게 식별하는 프로필 ID입니다.

앱에서 다음 단계에 따라 이 요청을 처리해야 합니다.

  1. action 필드의 값이 open이고 ids 필드가 다음과 같은지 확인합니다. 있습니다.
  2. userId 값을 사용하여 사용자의 새 세션을 만듭니다. 자세히 알아보기 자세한 내용은 사용자 및 새 이벤트를 사용합니다.
  3. files.get 메서드를 사용하여 파일 메타데이터를 가져오고, API를 사용하여 파일 콘텐츠를 ID 값입니다.
  4. 요청에 resourceKeys가 설정된 경우 X-Goog-Drive-Resource-Keys 요청 헤더. 자세한 내용은 리소스를 사용하여 링크 공유 파일에 액세스 키를 참조하세요.

state 매개변수는 URL로 인코딩되므로 앱에서 이스케이프를 처리해야 합니다. JSON으로 파싱합니다

Google Workspace 문서의 공개 URL 처리

Drive UI 구성 통합되는 경우 앱에 기본 기능 모음이 수신됩니다. state 매개변수 내 템플릿 변수. 기본 state 정보 Google Workspace Open URL의 특징은 다음과 같습니다.

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

이 출력에는 다음 값이 포함됩니다.

  • EXPORT_ID: 쉼표로 구분된 파일 ID 목록입니다. 내보냄 (내장된 Google 문서를 열 때만 사용됨)
  • RESOURCE_KEYS: 매핑된 파일 ID의 JSON 사전 해당 리소스 키를 줄일 수 있습니다
  • open: 수행 중인 동작입니다. Open()을 사용하는 경우 값은 open입니다. URL입니다.
  • USER_ID: 사용자를 식별하는 프로필 ID입니다.

앱에서 다음 단계에 따라 이 요청을 처리해야 합니다.

  1. open를 모두 감지하여 이 요청이 파일 열기 요청인지 확인합니다. state 필드의 값과 exportIds 필드의 존재 여부

  2. files.get 메서드를 사용하여 파일 메타데이터를 가져오고, EXPORT_ID 값.

  3. 다음을 사용하여 파일 콘텐츠를 변환합니다. files.export 메서드를 사용하여 지도 가장자리에 패딩을 추가할 수 있습니다. 다음 Google Workspace 문서를 요청한 MIME 유형입니다.

  4. 요청에 resourceKey가 설정된 경우 X-Goog-Drive-Resource-Keys 요청 헤더. 자세한 내용은 리소스를 사용하여 링크 공유 파일에 액세스 키를 참조하세요.

    자바

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

    2,399필리핀

    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 매개변수는 URL로 인코딩되므로 앱에서 이스케이프를 처리해야 합니다. JSON으로 파싱합니다

사용자 및 새 이벤트

드라이브 앱은 모든 '다음으로 열기'를 취급해야 함 이벤트를 잠재적 이벤트로 있습니다. 일부 사용자에게는 여러 계정이 있을 수 있으므로 state의 사용자 ID는 매개변수가 현재 세션과 일치하지 않을 수 있습니다. state의 사용자 ID가 매개변수가 현재 세션과 일치하지 않는 경우 캠페인의 현재 세션을 종료하세요. 앱을 열고 요청된 사용자로 로그인합니다.

애플리케이션은 Google Drive UI에서 애플리케이션을 여는 것 외에도 앱 내에서 콘텐츠를 선택하는 파일 선택 도구를 표시합니다. 자세히 알아보기 정보는 Google 선택 도구를 참고하세요.