Create Files

By responding to actions launched from the prominent Create button in the Google Drive UI, apps can create Drive files as well as shortcuts to files stored outside of Drive. To see what the UI options look like, read the overview What Can You do with the Drive platform?.

Create a new file from the Drive UI

When a user selects Create > More in Google Drive, they'll see applications that have registered a URL for creating files. Then, when the user selects an app from the menu list, Drive redirects the user to that app's Open URL (this URL is defined when you enable the Drive platform).

The redirected request from the user's browser contains the following important information in the state parameter:

  • The action, set to create.
  • The folderId, which identifies the parent folder.
  • The userId, which identifies the authenticated user.

Instead of the state parameter, you may opt to use template variable substitution to construct the request URL instead.

The state parameter is URL-encoded, so you'll need to handle the escape characters and parse it as JSON. In JSON notation, state information from a "create" URL looks like the following:

{
  "action":"create",
  "folderId":"0ADK06pfg",
  "userId":"103354693083460731603"
}

Apps can detect the create value in the state parameter to verify that this is a request to create a new file.

For guidance on uploading the new file's metadata and content to Drive, see examples and reference information for the files.create method.

Create a shortcut to a file

To create a shortcut instead of a file stored in Drive, use the files.create method of the API and make sure you set the MIME type application/vnd.google-apps.drive-sdk. Do not upload any content when creating the file.

Java

File fileMetadata = new File();
fileMetadata.setName("Project plan");
fileMetadata.setMimeType("application/vnd.google-apps.drive-sdk");

File file = driveService.files().create(fileMetadata)
    .setFields("id")
    .execute();
System.out.println("File ID: " + file.getId());

Python

file_metadata = {
    'name': 'Project plan',
    'mimeType': 'application/vnd.google-apps.drive-sdk'
}
file = drive_service.files().create(body=file_metadata,
                                    fields='id').execute()
print 'File ID: %s' % file.get('id')

PHP

$fileMetadata = new Google_Service_Drive_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);

.NET

var fileMetadata = new File()
{
    Name = "Project plan",
    MimeType = "application/vnd.google-apps.drive-sdk"
};
var request = driveService.Files.Create(fileMetadata);
request.Fields = "id";
var file = request.Execute();
Console.WriteLine("File ID: " + file.Id);

Ruby

file_metadata = {
    name: 'Project plan',
    mime_type: 'application/vnd.google-apps.drive-sdk'
}
file = drive_service.create_file(file_metadata, fields: 'id')
puts "File Id: #{file.id}"

Node.js

var fileMetadata = {
  'name': 'Project plan',
  'mimeType': 'application/vnd.google-apps.drive-sdk'
};
drive.files.create({
  resource: fileMetadata,
  fields: 'id'
}, function (err, file) {
  if (err) {
    // Handle error
    console.error(err);
  } else {
    console.log('File Id: ', file.id);
  }
});

Objective-C

GTLRDrive_File *metadata = [GTLRDrive_File object];
metadata.name = @"Project plan";
metadata.mimeType = @"application/vnd.google-apps.drive-sdk";
GTLRDriveQuery_FilesCreate *query = [GTLRDriveQuery_FilesCreate queryWithObject:metadata
                                     uploadParameters:nil];
query.fields = @"id";
[driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
                                                     GTLRDrive_File *file,
                                                     NSError *error) {
    if (error == nil) {
        NSLog(@"File ID %@", file.identifier);
    } else {
        NSLog(@"An error occurred: %@", error);
    }
}];

When updating shortcuts, you can use files.update to set the modifiedTime of the file. This ensures it displays and is sorted properly in the Drive UI.

Java

String fileId = "1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ";
File fileMetadata = new File();
fileMetadata.setModifiedTime(new DateTime(System.currentTimeMillis()));
File file = driveService.files().update(fileId, fileMetadata)
    .setFields("id, modifiedTime")
    .execute();
System.out.println("Modified time: " + file.getModifiedTime());

Python

file_id = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
file_metadata = {
    'modifiedTime': datetime.utcnow().isoformat() + 'Z'
}
file = drive_service.files().update(fileId=file_id,
                                    body=file_metadata,
                                    fields='id, modifiedTime').execute()
print 'Modified time: %s' % file.get('modifiedTime')

PHP

$fileId = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
$fileMetadata = new Google_Service_Drive_DriveFile(array(
    'modifiedTime' => date('Y-m-d\TH:i:s.uP')));
$file = $driveService->files->update($fileId, $fileMetadata, array(
    'fields' => 'id, modifiedTime'));
printf("Modified time: %s\n", $file->modifiedTime);

.NET

var fileId = "1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ";
var fileMetadata = new File()
{
    ModifiedTime = DateTime.Now
};
var request = driveService.Files.Update(fileMetadata, fileId);
request.Fields = "id, modifiedTime";
var file = request.Execute();
Console.WriteLine("Modified time: " + file.ModifiedTime);

Ruby

file_id = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
file_metadata = {
    modified_time: DateTime.now
}
file = drive_service.update_file(file_id,
                                 file_metadata,
                                 fields: 'id, modifiedTime')
puts "Modified time: #{file.modified_time}"

Node.js

fileId = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
var fileMetadata = {
  'modifiedTime': new Date().toISOString()
};
drive.files.update({
  fileId: fileId,
  resource: fileMetadata,
  fields: 'id, modifiedTime'
}, function (err, file) {
  if (err) {
    // Handle error
    console.error(err);
  } else {
    console.log('Modified time: ', file.modifiedTime);
  }
});

Objective-C

NSString *fileId = @"1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ";
GTLRDrive_File *metadata = [GTLRDrive_File object];
metadata.modifiedTime = [GTLRDateTime dateTimeWithDate:[NSDate date]];

GTLRDriveQuery_FilesUpdate *query = [GTLRDriveQuery_FilesUpdate queryWithObject:metadata
                                                                         fileId:fileId
                                                               uploadParameters:nil];
query.fields = @"id, modifiedTime";
[driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
                                                     GTLRDrive_File *file,
                                                     NSError *error) {
    if (error == nil) {
        NSLog(@"Modified time: %@", [file.modifiedTime stringValue]);
    } else {
        NSLog(@"An error occurred: %@", error);
    }
}];

Adding custom thumbnails and indexable text

To increase the discoverability of files associated with shortcuts, you can upload both thumbnail images and indexable text when inserting or modifying the file metadata. For more information, see Manage File Metadata.

发送以下问题的反馈:

此网页
Drive REST API
Drive REST API