ผสานรวมกับ UI ของไดรฟ์"เปิดด้วย"

เมื่อผู้ใช้เลือกไฟล์แล้วคลิกรายการเมนู เปิดด้วย ของ UI ไดรฟ์ ไดรฟ์จะเปลี่ยนเส้นทาง ผู้ใช้ไปยัง URL ที่เปิดของแอปนั้นซึ่งกำหนดไว้ในหัวข้อกำหนดค่าการผสานรวม UI ไดรฟ์

หากคุณเลือกช่อง "กำลังนำเข้า" เมื่อกำหนดค่าการผสานรวม UI ไดรฟ์ ผู้ใช้จะเลือกไฟล์ที่เฉพาะเจาะจงของแอปและไฟล์ Google Workspace ร่วมกันเพื่อเปิดได้ เมื่อกำหนดค่าการผสานรวม UI ไดรฟ์ ระบบจะกำหนดไฟล์ที่เฉพาะเจาะจงของแอปในช่อง "ประเภท MIME เริ่มต้น" และ "ส่วนขยายไฟล์เริ่มต้น" ส่วนไฟล์ Google Workspace จะกำหนดไว้ในช่อง "ประเภท MIME รอง" และ "ส่วนขยายไฟล์รอง"

สำหรับไฟล์แต่ละไฟล์ที่ผู้ใช้ต้องการเปิด ไดรฟ์จะตรวจสอบประเภท MIME กับประเภท MIME เริ่มต้นและรองที่คุณกำหนดไว้ ดังนี้

  • สำหรับประเภท MIME ที่กำหนดไว้ในช่อง "ประเภท MIME เริ่มต้น" ระบบจะส่งรหัสไฟล์ไปยังแอปของคุณ ดูข้อมูลเกี่ยวกับวิธีจัดการไฟล์ที่เฉพาะเจาะจงของแอปได้ที่หัวข้อ จัดการ URL ที่เปิดสำหรับเอกสารที่เฉพาะเจาะจงของแอป

  • สำหรับประเภท MIME ที่กำหนดไว้ในช่อง "ประเภท MIME รอง" UI ไดรฟ์จะแสดงกล่องโต้ตอบเพื่อถามผู้ใช้ว่าต้องการแปลงไฟล์ Google Workspace เป็นไฟล์ประเภทใด ตัวอย่างเช่น หากคุณเลือกไฟล์ Google เอกสารใน UI ไดรฟ์ และช่อง "ประเภท MIME รอง" แนะนำว่าแอปของคุณรองรับ text/plain หรือ application/pdf UI ไดรฟ์จะถามผู้ใช้ว่าต้องการแปลงเป็นข้อความธรรมดาหรือ PDF หรือไม่

    ดูข้อมูลเกี่ยวกับวิธีจัดการไฟล์ Google Workspace ได้ที่หัวข้อจัดการ URL ที่เปิดสำหรับเอกสาร Google Workspace ดูรายการเอกสาร Google Workspace และรูปแบบการแปลงประเภท MIME ได้ที่ หัวข้อส่งออกประเภท MIME สำหรับ Google Workspace เอกสาร

จัดการ URL ที่เปิดสำหรับเอกสารที่เฉพาะเจาะจงของแอป

ดังที่กล่าวไว้ในหัวข้อกำหนดค่าการผสานรวม UI ไดรฟ์, แอปของคุณจะได้รับตัวแปรเทมเพลตพร้อมข้อมูลเพื่อให้แอปเปิด ไฟล์ได้ แอปของคุณจะได้รับชุดตัวแปรเทมเพลตเริ่มต้น ภายในพารามิเตอร์ state ข้อมูล state เริ่มต้นสำหรับ URL ที่เปิดของแอปมีดังนี้

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

เอาต์พุตนี้มีค่าต่อไปนี้

  • ID: รหัสของโฟลเดอร์หลัก
  • RESOURCE_KEYS: พจนานุกรม JSON ของรหัสไฟล์ที่แมปกับ คีย์ทรัพยากรที่เกี่ยวข้อง
  • open: การดำเนินการที่กำลังดำเนินการ ค่าจะเป็น open เมื่อใช้ URL ที่เปิด
  • USER_ID: รหัสโปรไฟล์ที่ระบุผู้ใช้ที่ไม่ซ้ำกัน

แอปของคุณต้องดำเนินการตามคำขอนี้โดยทำตามขั้นตอนต่อไปนี้

  1. ตรวจสอบว่าช่อง action มีค่าเป็น open และมีช่อง ids
  2. ใช้ค่า userId เพื่อสร้างเซสชันใหม่สำหรับผู้ใช้ ดูข้อมูลเพิ่มเติมเกี่ยวกับผู้ใช้ที่ลงชื่อเข้าใช้ได้ที่หัวข้อผู้ใช้และเหตุการณ์ใหม่
  3. ใช้วิธี files.get เพื่อตรวจสอบ สิทธิ์ ดึงข้อมูลเมตาของไฟล์ และดาวน์โหลดเนื้อหาไฟล์โดยใช้ ค่า ID
  4. หากตั้งค่า resourceKeys ในคำขอ ให้ตั้งค่าส่วนหัวของคำขอ X-Goog-Drive-Resource-Keys ดูข้อมูลเพิ่มเติมเกี่ยวกับ คีย์ทรัพยากรได้ที่หัวข้อเข้าถึงไฟล์ที่แชร์ผ่านลิงก์โดยใช้คีย์ทรัพยากร

พารามิเตอร์ state ได้รับการเข้ารหัส URL ดังนั้นแอปของคุณต้องจัดการอักขระหลีกและแยกวิเคราะห์เป็น JSON

จัดการ URL ที่เปิดสำหรับเอกสาร Google Workspace

ดังที่กล่าวไว้ในหัวข้อกำหนดค่าการผสานรวม UI ไดรฟ์ แอปของคุณจะได้รับชุดตัวแปรเทมเพลตเริ่มต้น ภายในพารามิเตอร์ state ข้อมูล state เริ่มต้นสำหรับ URL ที่เปิดของ Google Workspace มีดังนี้

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

เอาต์พุตนี้มีค่าต่อไปนี้

  • EXPORT_ID: รายการรหัสไฟล์ที่คั่นด้วยคอมมาซึ่งกำลังส่งออก ใช้เมื่อเปิดไฟล์ Google Workspace เท่านั้น
  • RESOURCE_KEYS: พจนานุกรม JSON ของรหัสไฟล์ที่แมปกับ คีย์ทรัพยากรที่เกี่ยวข้อง
  • open: การดำเนินการที่กำลังดำเนินการ ค่าจะเป็น open เมื่อใช้ URL ที่เปิด
  • USER_ID: รหัสโปรไฟล์ที่ระบุผู้ใช้

แอปของคุณต้องดำเนินการตามคำขอนี้โดยทำตามขั้นตอนต่อไปนี้

  1. ตรวจสอบว่านี่เป็นคำขอให้เปิดไฟล์โดยตรวจหาทั้งค่า open ในช่อง state และการมีช่อง exportIds

  2. ใช้วิธี files.get เพื่อตรวจสอบ สิทธิ์ ดึงข้อมูลเมตาของไฟล์ และกำหนดประเภท MIME โดยใช้ค่า EXPORT_ID

  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
    import {GoogleAuth} from 'google-auth-library';
    import {google} from 'googleapis';
    
    /**
     * Exports a Google Doc as a PDF.
     * @param {string} fileId The ID of the file to export.
     * @return {Promise<number>} The status of the export request.
     */
    async function exportPdf(fileId) {
      // Authenticate with Google and get an authorized client.
      // TODO (developer): Use an appropriate auth mechanism for your app.
      const auth = new GoogleAuth({
        scopes: 'https://www.googleapis.com/auth/drive',
      });
    
      // Create a new Drive API client (v3).
      const service = google.drive({version: 'v3', auth});
    
      // Export the file as a PDF.
      const result = await service.files.export({
        fileId,
        mimeType: 'application/pdf',
      });
    
      // Print the status of the export.
      console.log(result.status);
      return result.status;
    }

    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 ได้รับการเข้ารหัส URL ดังนั้นแอปของคุณต้องจัดการอักขระหลีกและแยกวิเคราะห์เป็น JSON

ผู้ใช้และเหตุการณ์ใหม่

แอปไดรฟ์ควรถือว่าเหตุการณ์ "เปิดด้วย" ทั้งหมดเป็นการลงชื่อเข้าใช้ที่อาจเกิดขึ้น ผู้ใช้บางรายอาจมีหลายบัญชี ดังนั้นรหัสผู้ใช้ในพารามิเตอร์ state อาจไม่ตรงกับเซสชันปัจจุบัน หากรหัสผู้ใช้ในพารามิเตอร์ state ไม่ตรงกับเซสชันปัจจุบัน ให้สิ้นสุดเซสชันปัจจุบันสำหรับแอปของคุณและลงชื่อเข้าใช้ในฐานะผู้ใช้ที่ขอ

นอกจากการเปิดแอปพลิเคชันจาก UI ของ Google ไดรฟ์แล้ว แอปพลิเคชันยังสามารถแสดงเครื่องมือเลือกไฟล์เพื่อเลือกเนื้อหาจากภายในแอปได้ด้วย ดูข้อมูลเพิ่มเติมได้ที่ Google Picker