앱에 저장된 콘텐츠의 바로가기 파일 만들기

Google Drive의 타사 바로가기는 타사 소유의 외부 스토리지 시스템에 있는 다른 파일에 연결되는 메타데이터 전용 파일입니다. 이러한 바로가기는 일반적으로 다른 Datastore 또는 클라우드 스토리지 시스템에 있는 Drive 외부 애플리케이션이 저장한 '콘텐츠' 파일의 참조 링크 역할을 합니다.

서드 파티 바로가기를 만들려면 Google Drive API의 files.create 메서드를 사용하고 MIME 유형을 application/vnd.google-apps.drive-sdk로 설정합니다. 파일을 만들 때 콘텐츠를 업로드하지 마세요. 자세한 내용은 Google Workspace 및 Google Drive에서 지원하는 MIME 유형을 참고하세요.

서드 파티 바로가기는 업로드 또는 다운로드할 수 없습니다.

다음 코드 샘플은 클라이언트 라이브러리를 사용하여 서드 파티 바로가기를 만드는 방법을 보여줍니다.

Java

drive/snippets/drive_v3/src/main/java/CreateShortcut.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.api.services.drive.model.File;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Arrays;

/* Class to demonstrate Drive's create shortcut use-case */
public class CreateShortcut {

  /**
   * Creates shortcut for file.
   *
   * @throws IOException if service account credentials file not found.
   */
  public static String createShortcut() 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();
    try {
      // Create Shortcut for file.
      File fileMetadata = new File();
      fileMetadata.setName("Project plan");
      fileMetadata.setMimeType("application/vnd.google-apps.drive-sdk");

      File file = service.files().create(fileMetadata)
          .setFields("id")
          .execute();
      System.out.println("File ID: " + file.getId());
      return file.getId();
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      System.err.println("Unable to create shortcut: " + e.getDetails());
      throw e;
    }
  }
}

Python

drive/snippets/drive-v3/file_snippet/create_shortcut.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def create_shortcut():
  """Create a third party shortcut

  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_metadata = {
        "name": "Project plan",
        "mimeType": "application/vnd.google-apps.drive-sdk",
    }

    # pylint: disable=maybe-no-member
    file = service.files().create(body=file_metadata, fields="id").execute()
    print(f'File ID: {file.get("id")}')

  except HttpError as error:
    print(f"An error occurred: {error}")
  return file.get("id")


if __name__ == "__main__":
  create_shortcut()

2,399필리핀

drive/snippets/drive_v3/src/DriveCreateShortcut.php
use Google\Client;
use Google\Service\Drive;
use Google\Service\Drive\DriveFile;
function createShortcut()
{
    try {

        $client = new Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);
        $fileMetadata = new DriveFile(array(
            'name' => 'Project plan',
            'mimeType' => 'application/vnd.google-apps.drive-sdk'));
        $file = $driveService->files->create($fileMetadata, array(
            'fields' => 'id'));
        printf("File ID: %s\n", $file->id);
        return $file->id;

    } catch(Exception $e) {
        echo "Error Message: ".$e;
    }

}

.NET

drive/snippets/drive_v3/DriveV3Snippets/CreateShortcut.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;

namespace DriveV3Snippets
{
    // Class to demonstrate Drive's create shortcut use-case
    public class CreateShortcut
    {
        /// <summary>
        /// Create a third party shortcut.
        /// </summary>
        /// <returns>newly created shortcut file id, null otherwise.</returns>
        public static string DriveCreateShortcut()
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for 
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential
                    .GetApplicationDefault()
                    .CreateScoped(DriveService.Scope.Drive);

                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Snippets"
                });

                // Create Shortcut for file.
                var fileMetadata = new Google.Apis.Drive.v3.Data.File()
                {
                    Name = "Project plan",
                    MimeType = "application/vnd.google-apps.drive-sdk"
                };
                var request = service.Files.Create(fileMetadata);
                request.Fields = "id";
                var file = request.Execute();
                // Prints the shortcut file id.
                Console.WriteLine("File ID: " + file.Id);
                return file.Id;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}

Node.js

drive/snippets/drive_v3/file_snippets/create_shortcut.js
/**
 * Create a third party shortcut
 * @return{obj} shortcut Id
 * */
async function createShortcut() {
  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app

  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const fileMetadata = {
    name: 'Project plan',
    mimeType: 'application/vnd.google-apps.drive-sdk',
  };

  try {
    const file = await service.files.create({
      resource: fileMetadata,
      fields: 'id',
    });
    console.log('File Id:', file.data.id);
    return file.data.id;
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}

서드 파티 바로가기 작동 방식

files.create 메서드를 사용하여 서드 파티 바로가기를 만들면 POST 요청을 사용하여 메타데이터를 삽입하고 앱 콘텐츠의 바로가기를 만듭니다.

POST https://www.googleapis.com/drive/v3/files
Authorization: AUTHORIZATION_HEADER

{
  "title": "FILE_TITLE",
  "mimeType": "application/vnd.google-apps.drive-sdk"
}

서드 파티 바로가기를 클릭하면 사용자가 파일이 있는 외부 사이트로 리디렉션됩니다. Drive 파일 ID는 state 매개변수에 포함됩니다. 자세한 내용은 앱별 문서의 Open URL 처리를 참고하세요.

그러면 서드 파티 앱 또는 웹사이트에서 state 매개변수의 파일 ID를 시스템 내에 저장된 콘텐츠와 일치시켜야 합니다.

맞춤 썸네일 및 색인 생성이 가능한 텍스트 추가

서드 파티 바로가기와 연결된 파일의 검색 가능성을 높이기 위해 파일 메타데이터를 삽입하거나 수정할 때 썸네일 이미지와 색인 생성 가능한 텍스트를 모두 업로드할 수 있습니다. 자세한 내용은 파일 메타데이터 관리를 참고하세요.