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

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

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

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

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

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

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

จัดการ Open URL สำหรับเอกสารเฉพาะแอป

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

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

ผลลัพธ์นี้ประกอบด้วยค่าต่อไปนี้

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

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

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

พารามิเตอร์ state เข้ารหัส URL แอปจึงต้องจัดการ Escape แล้วแยกวิเคราะห์เป็น 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 ในตัวเท่านั้น)
  • RESOURCE_KEYS: พจนานุกรม JSON ของรหัสไฟล์ที่แมปกับ คีย์ทรัพยากรที่เกี่ยวข้อง
  • open: การดำเนินการที่กำลังทำ ค่าคือ 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
    /**
     * 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 เข้ารหัส URL แอปจึงต้องจัดการ Escape แล้วแยกวิเคราะห์เป็น JSON

ผู้ใช้และ กิจกรรมใหม่

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

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