为文件设置标签字段

本页面介绍如何为单个 Google 云端硬盘文件设置标签 Field

如需通过设置文件标签向文件添加元数据,请使用 files.modifyLabels 方法。请求正文包含一个 ModifyLabelsRequest 实例,用于修改文件上的标签集。请求可能包含多项以原子方式应用的修改。也就是说,如果任何修改无效,则整个更新都将失败,并且不会应用任何(可能相关的)更改。

ModifyLabelsRequest 包含 LabelModification 的一个实例,该实例是对文件标签的修改。它还可能包含 FieldModification 的实例,该实例是对标签字段的修改。

如果成功,响应正文将包含请求添加或更新的标签。这些按钮位于类型为 LabelmodifiedLabels 对象中。

示例

以下代码示例展示了如何使用文本字段的 fieldId 在文件中设置此 Field 的值。最初在文件中设置标签 Field 时,会将标签应用于文件。然后,您可以取消设置单个字段或移除与该标签关联的所有字段。如需了解详情,请参阅取消设置文件的标签字段移除文件的标签

Java

LabelFieldModification fieldModification =
new LabelFieldModification().setFieldId("FIELD_ID").setSetTextValues(ImmutableList.of("VALUE"));

ModifyLabelsRequest modifyLabelsRequest =
  new ModifyLabelsRequest()
      .setLabelModifications(
          ImmutableList.of(
              new LabelModification()
                .setLabelId("LABEL_ID")
                .setFieldModifications(ImmutableList.of(fieldModification))));

ModifyLabelsResponse modifyLabelsResponse = driveService.files().modifyLabels("FILE_ID", modifyLabelsRequest).execute();

Python

field_modification = {'fieldId':'FIELD_ID','setTextValues':['VALUE']}
label_modification = {'labelId':'LABEL_ID', 'fieldModifications':[field_modification]}

modified_labels = drive_service.files().modifyLabels(fileId="FILE_ID", body = {'labelModifications' : [label_modification]}).execute();

Node.js

/**
* Set a label with a text field on a Drive file
* @return{obj} updated label data
**/
async function setLabelTextField() {
  // 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 fieldModification = {
    'fieldId': 'FIELD_ID',
    'setTextValues': ['VALUE'],
  };
  const labelModification = {
    'labelId': 'LABEL_ID',
    'fieldModifications': [fieldModification],
  };
  const labelModificationRequest = {
    'labelModifications': [labelModification],
  };
  try {
    const updateResponse = await service.files.modifyLabels({
      fileId: 'FILE_ID',
      resource: labelModificationRequest,
    });
    return updateResponse;
  } catch (err) {
    // TODO (developer) - Handle error
    throw err;
  }
}

替换以下内容:

  • FIELD_ID:要修改的字段的 fieldId。如需找到 fieldId,请使用 Google Drive Labels API 检索标签。
  • VALUE:此字段的新 value
  • LABEL_ID:要修改的标签的 labelId
  • FILE_ID:修改了标签的文件的 fileId

备注

  • 如需设置不含字段的标签,请应用不含 fieldModificationslabelModifications
  • 如需为选择字段选项设置值,请使用相应值的 Choice ID。您可以通过在 Drive Labels API 中提取标签架构来获取该值。
  • 只有支持值列表的 Field 才可以设置多个值,否则您将收到 400: Bad Request 错误响应。
  • 为选定的 Field 设置适当的值类型(例如整数、文本、用户等),否则您将收到 400: Bad Request 错误响应。您可以使用 Drive Labels API 检索字段数据类型。