上传数据到共享驱动器使用Java中的服务帐户

huangapple go评论88阅读模式
英文:

Uploading data to shared drive using service account in java

问题

我想使用Java将文件上传到共享驱动器。
我已经创建了一个服务帐户,并且已经与服务帐户的地址共享了共享驱动器(名称为DB-Drive)。

全局变量

private static HttpTransport httpTransport;
private static Drive drive;

主要函数(初始化和列出文件)

httpTransport = GoogleNetHttpTransport.newTrustedTransport();
Credential credential = authorize();
drive = new Drive.Builder(httpTransport, JacksonFactory.getDefaultInstance(), credential).setApplicationName(
    "Quickstart").build();

uploadFile();

FileList result = drive.files().list().execute();
List<File> files = result.getFiles();
if (result == null || result.isEmpty()) {
    System.out.println("No files found.");
} else {
    System.out.println("Files:");
    for (File file : files) {
        System.out.printf("%s %s \n", file.getName(), file.getId());
    }
}

授权代码

GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("resources/credentials.json"))
    .createScoped(Collections.singleton(DriveScopes.DRIVE_FILE));

return credential;

上传代码

String folderId = "***DB-Drive id****";
File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
fileMetadata.setParents(Collections.singletonList(folderId));
java.io.File filePath = new java.io.File("/home/*****/Downloads/qck_1552369371.jpeg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = drive.files().create(fileMetadata, mediaContent)
    .setFields("id, parents")
    .execute();
System.out.println("File ID: " + file.getId());
return file;

我正在将DB-Drive设置为上传文件的父级,但仍然无法在共享驱动器文件夹中查看它。请帮助我。

我正在添加完整的流程:

1.) 我使用https://developers.google.com/identity/protocols/oauth2/service-account上的步骤创建了服务帐户。
我选择了项目并提供了描述等信息。

2.) 我没有为服务帐户提供域级别的委派,而是使用了服务帐户地址共享了DB-drive(团队驱动器)(该地址在credentials.json文件中作为client_email *****.gserviceaccount.com进行了提及)。

3.) 然后,我使用上面的代码要求服务帐户将文件上传到共享驱动器,即DB-Drive,通过指定DB-Drive的ID作为文件的父ID。

4.) 但是文件仍然上传到服务帐户的驱动器,而没有链接到共享驱动器。

5.) DB-Drive是父文件夹(唯一的文件夹)。

任何线索都将是极大的帮助。

英文:

I want to upload the files to shared drive using java.
I have created a service account and I have shared the shared-drive (name is DB-Drive) with the service account's address.

Global variables

private static HttpTransport httpTransport;
private static Drive drive;

Main function (initialize and listing of the files)

    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    Credential credential = authorize();
    drive = new Drive.Builder(httpTransport, JacksonFactory.getDefaultInstance(), credential).setApplicationName(
                    &quot;Quickstart&quot;).build();

    uploadFile();

    FileList result = drive.files().list().execute();
    List&lt;File&gt; files = result.getFiles();
    if (result == null || result.isEmpty()) {
        System.out.println(&quot;No files found.&quot;);
      } else {
        System.out.println(&quot;Files:&quot;);
        for (File file : files) {
             System.out.printf(&quot;%s %s \n&quot;, file.getName(),file.getId());
                }
            }
        } 

Authorization code

        GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(&quot;resources/credentials.json&quot;))
                .createScoped(Collections.singleton(DriveScopes.DRIVE_FILE));

        return credential;

Uploading code

 String folderId = &quot;***DB-Drive id****&quot;;
        File fileMetadata = new File();
        fileMetadata.setName(&quot;photo.jpg&quot;);
        fileMetadata.setParents(Collections.singletonList(folderId));
        java.io.File filePath = new java.io.File(&quot;/home/*****/Downloads/qck_1552369371.jpeg&quot;);
        FileContent mediaContent = new FileContent(&quot;image/jpeg&quot;, filePath);
        File file = drive.files().create(fileMetadata, mediaContent)
                .setFields(&quot;id, parents&quot;)
                .execute();
        System.out.println(&quot;File ID: &quot; + file.getId());
        return file;

I am setting DB-Drive which is the teamdrive or the shareddrive as the parent of the uploaded file but still I am not able to view this in the shared drive folder.. Please help me with this.

I am adding the complete flow :-

1.) I create the service account using the steps mentioned at https://developers.google.com/identity/protocols/oauth2/service-account
I selected the project and gave the description and everything.

2.) I did'nt gave domain level delegation to service account rather I shared the DB-drive(team drive) with service account address (which was mentioned in credentials.json file as client_email *****.gserviceaccount.com)

3.) Then I used the above code to upload the file asking service account to upload the file to shared drive i.e DB-Drive by specifying the DB-Drive's id as the parent id of the file.

4.) but still the file is getting uploaded to service account's drive it is not getting linked to shared drive.

5.) DB-Drive is the parent folder (the only folder).

Any leads would be a great help.

答案1

得分: 3

如 @ziganotschka 指出的,如果要在共享驱动器中创建文件,您需要将 supportsAllDrives 设置为 true。Java 客户端的 setSupportsTeamDrives 选项已被弃用。而是使用 setSupportsAllDrives 设置为 true。


当您在使用服务帐户将文件上传到共享驱动器时遇到问题,您应采取以下故障排除步骤:

  • 隔离问题
  • 自己问一下 - 问题是否与服务帐户的使用或其他事情有关?
  • 为此,请尝试在没有服务帐户的情况下进行相同的请求
  • 如果服务帐户被证明是问题的原因
    • 验证您是否在 GCP 控制台中正确启用了域代表授权
    • 验证您是否在管理控制台中为委派的服务帐户提供了正确的范围
  • 验证您的代码实现是否正确
  • 如果问题与服务帐户无关 - 验证是否与代码语法相关或与请求相关
  • 为此,请使用尝试此 API工具,在不编码的情况下测试您的请求
    • 如果问题与编码有关 - 调试您的代码
    • 如果问题与请求有关,则根据尝试此 API返回的错误采取行动
  • 如果收到 404 文件未找到 错误 - 这可能意味着
    • 文件位于共享驱动器上(在这种情况下,您必须将 supportsAllDrives 设置为 true,如上所述)
    • 或者 fileId 不正确
    • 或者文件对您用于身份验证的帐户不可访问
英文:

As @ziganotschka points out you need to set supportsAllDrives to true if creating a file in a shared drive. The Java client's setSupportsTeamDrives option is deprecated. Instead use setSupportsAllDrives to true.


When you have troubles uploading a file with a service ccount to a shared Drive, you should take the following steps for troubleshooting:

  • Isolate the problem
  • Ask yourself - is the problem related to the usage of the service account or something else?
  • For this, test the same request without a service account
  • If the service account turns out to be the culpit
    • Verify that you enabled domain-wide delegation correctly in the GCP console
    • Verify that you provided the correct scopes to the delegated service account in the Admin console
  • Verify that your code implementation is correct
  • If the problem is not service account related - verify either it is code syntax related or request related
  • For this, use the Try this API tool to test your request without coding
    • If the issue is coding related - debug your code
    • If the issue is request related, act according to the error the Try this API returns you
  • If you receive a 404 File not found error - it either means that
    • the file is located on a shared Drive (in this case you have to set supportsAllDrives to true as mentioned above)
    • or the fileId is not correct
    • Or the file is not accessible to the account you use for authentication

huangapple
  • 本文由 发表于 2020年8月10日 18:59:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63338864.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定