importcom.google.api.client.googleapis.json.GoogleJsonResponseException;importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.drive.Drive;importcom.google.api.services.drive.DriveScopes;importcom.google.api.services.drive.model.File;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importjava.io.IOException;importjava.util.Arrays;/* Class to demonstrate Drive's create shortcut use-case */publicclassCreateShortcut{/** * Creates shortcut for file. * * @throws IOException if service account credentials file not found. */publicstaticStringcreateShortcut()throwsIOException{/* Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application.*/GoogleCredentialscredentials=GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials);// Build a new authorized API client service.Driveservice=newDrive.Builder(newNetHttpTransport(),GsonFactory.getDefaultInstance(),requestInitializer).setApplicationName("Drive samples").build();try{// Create Shortcut for file.FilefileMetadata=newFile();fileMetadata.setName("Project plan");fileMetadata.setMimeType("application/vnd.google-apps.drive-sdk");Filefile=service.files().create(fileMetadata).setFields("id").execute();System.out.println("File ID: "+file.getId());returnfile.getId();}catch(GoogleJsonResponseExceptione){// TODO(developer) - handle error appropriatelySystem.err.println("Unable to create shortcut: "+e.getDetails());throwe;}}}
importgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpErrordefcreate_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 clientservice=build("drive","v3",credentials=creds)file_metadata={"name":"Project plan","mimeType":"application/vnd.google-apps.drive-sdk",}# pylint: disable=maybe-no-memberfile=service.files().create(body=file_metadata,fields="id").execute()print(f'File ID: {file.get("id")}')exceptHttpErroraserror:print(f"An error occurred: {error}")returnfile.get("id")if__name__=="__main__":create_shortcut()
usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Drive.v3;usingGoogle.Apis.Services;namespaceDriveV3Snippets{// Class to demonstrate Drive's create shortcut use-casepublicclassCreateShortcut{/// <summary>/// Create a third party shortcut./// </summary>/// <returns>newly created shortcut file id, null otherwise.</returns>publicstaticstringDriveCreateShortcut(){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. */GoogleCredentialcredential=GoogleCredential.GetApplicationDefault().CreateScoped(DriveService.Scope.Drive);// Create Drive API service.varservice=newDriveService(newBaseClientService.Initializer{HttpClientInitializer=credential,ApplicationName="Drive API Snippets"});// Create Shortcut for file.varfileMetadata=newGoogle.Apis.Drive.v3.Data.File(){Name="Project plan",MimeType="application/vnd.google-apps.drive-sdk"};varrequest=service.Files.Create(fileMetadata);request.Fields="id";varfile=request.Execute();// Prints the shortcut file id.Console.WriteLine("File ID: "+file.Id);returnfile.Id;}catch(Exceptione){// TODO(developer) - handle error appropriatelyif(eisAggregateException){Console.WriteLine("Credential Not found");}else{throw;}}returnnull;}}}
/** * Create a third party shortcut * @return{obj} shortcut Id * */asyncfunctioncreateShortcut(){// Get credentials and build service// TODO (developer) - Use appropriate auth mechanism for your appconst{GoogleAuth}=require('google-auth-library');const{google}=require('googleapis');constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/drive',});constservice=google.drive({version:'v3',auth});constfileMetadata={name:'Project plan',mimeType:'application/vnd.google-apps.drive-sdk',};try{constfile=awaitservice.files.create({requestBody:fileMetadata,fields:'id',});console.log('File Id:',file.data.id);returnfile.data.id;}catch(err){// TODO(developer) - Handle errorthrowerr;}}
第三方快捷方式的运作方式
当您使用 files.create 方法创建第三方快捷方式时,系统会使用 POST 请求插入元数据并创建指向应用内容的快捷方式:
POST https://www.googleapis.com/drive/v3/files
Authorization: AUTHORIZATION_HEADER
{
"title": "FILE_TITLE",
"mimeType": "application/vnd.google-apps.drive-sdk"
}
用户点击第三方快捷方式后,系统会将其重定向到存储文件的外部网站。云端硬盘文件 ID 包含在 state 参数中。如需了解详情,请参阅处理应用专用文档的打开网址。
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["没有我需要的信息","missingTheInformationINeed","thumb-down"],["太复杂/步骤太多","tooComplicatedTooManySteps","thumb-down"],["内容需要更新","outOfDate","thumb-down"],["翻译问题","translationIssue","thumb-down"],["示例/代码问题","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2024-12-21。"],[[["Third-party shortcuts in Google Drive are metadata-only files that link to files stored outside of Drive on external systems."],["To create a third-party shortcut, use the `files.create` method of the Google Drive API and set the MIME type to `application/vnd.google-apps.drive-sdk`."],["Third-party shortcuts can't be uploaded or downloaded, instead, they redirect users to the external location of the linked file when clicked."],["You can enhance the visibility of third-party shortcuts by adding custom thumbnails and indexable text to their metadata."]]],[]]