仅使用Java更新现有Google云端硬盘文件的元数据

问题描述 投票:3回答:2

我想只更新现有Google驱动器文件的元数据(例如描述或文件名),有一些文档可以使用javascript Google Drive Update Documentation。但没有Java文档。我也找到了这样做的代码

 private static File updateFile(Drive service, String fileId, String newTitle,
      String newDescription, String newMimeType, String newFilename, boolean newRevision) {
    try {
      // First retrieve the file from the API.
      File file = service.files().get(fileId).execute();

      // File's new metadata.
      file.setTitle(newTitle);
      file.setDescription(newDescription);
      file.setMimeType(newMimeType);

      // File's new content.
      java.io.File fileContent = new java.io.File(newFilename);
      FileContent mediaContent = new FileContent(newMimeType, fileContent);

      // Send the request to the API.
      File updatedFile = service.files().update(fileId, file, mediaContent).execute();

      return updatedFile;
    } catch (IOException e) {
      System.out.println("An error occurred: " + e);
      return null;
    }
  }

  // ...
}

但在此,它还更新内容(我不想这样做)。我怎样才能实现这一目标?

java android google-drive-android-api
2个回答
1
投票

根据更新元数据的文档,您有单独的URL,

上传URI,用于媒体上传请求:

PUT https://www.googleapis.com/upload/drive/v2/files/fileId

元数据URI,仅用于元数据请求:

PUT https://www.googleapis.com/drive/v2/files/fileId

更多关于,

https://developers.google.com/drive/api/v2/reference/files/update#try-it

它与java无关。点击正确的URL好友。

他们有java样本来更新元数据(仅限),

https://developers.google.com/drive/api/v2/reference/files/patch

代码:

import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.model.File;

import java.io.IOException;
// ...

public class MyClass {

  // ...

  /**
   * Rename a file.
   *
   * @param service Drive API service instance.
   * @param fileId ID of the file to rename.
   * @param newTitle New title for the file.
   * @return Updated file metadata if successful, {@code null} otherwise.
   */
  private static File renameFile(Drive service, String fileId, String newTitle) {
    try {
      File file = new File();
      file.setTitle(newTitle);

      // Rename the file.
      Files.Patch patchRequest = service.files().patch(fileId, file);
      patchRequest.setFields("title");

      File updatedFile = patchRequest.execute();
      return updatedFile;
    } catch (IOException e) {
      System.out.println("An error occurred: " + e);
      return null;
    }
  }

  // ...
}

1
投票

经过更多的研究,我找到了解决方案,

   File file =new File();
     file.setName("new name");
     service.files().update(fileid, file).execute();

此代码将更新文件的名称。

© www.soinside.com 2019 - 2024. All rights reserved.