【问题标题】:Upload to Google Drive not working using oauth PlayGround (java)使用 oauth PlayGround (java) 上传到 Google Drive 不起作用
【发布时间】:2020-02-17 18:55:24
【问题描述】:

我想使用 google drive api 使用 java 将一些文件上传到我的驱动器 问题是上传成功但是当我打开我的驱动器时我找不到文件所以我编辑了权限并添加了我的电子邮件(与我分享)但我无法下载文件只有上传的名称知道为什么吗?

public static void connect() throws IOException, GeneralSecurityException {
    UL.debug("Creating HTTP_TRANSPORT & a JSON_FACTORY");
    HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();

    UL.debug("Login-in with credentials");
    GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(CREDENTIALS_FILE))
            .createScoped(Collections.singleton(DriveScopes.DRIVE));

    UL.debug("User: " + credential.getServiceAccountUser() + " ID: " + credential.getServiceAccountProjectId());
    UL.debug("Creating Drive Instance");
    DRIVE_SERVICE = new Drive.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName("Backup")
            .build();

}


public static void upload() throws IOException {
    UL.debug("Creating file metadata");
    File fileMetadata = new File();
    fileMetadata.setName("Test");
    fileMetadata.setMimeType("application/rar");

    UL.debug("creating new filepath");
    java.io.File filePath = new java.io.File(DATA_FOLDER, "test3.rar");

    UL.debug("Creating file content (rar)");
    FileContent rarContent = new FileContent("application/rar", filePath);

    UL.debug("Pushing the file to drive !");
    Drive.Files.Create upload = DRIVE_SERVICE.files().create(fileMetadata, rarContent);
    upload.getMediaHttpUploader().setProgressListener(new FileUploadProgressListener());
    upload.setFields("*");

    File e = upload.execute();

    UL.debug("Push success: " + e.getId() + " " + e.getName() + " " + e.getMimeType());

    Permission newPermission = new Permission();

    newPermission.setEmailAddress("eaglezledozo@gmail.com");
    newPermission.setType("user");
    newPermission.setRole("writer");
    DRIVE_SERVICE.permissions().create(e.getId(), newPermission).execute();
}

【问题讨论】:

    标签: java oauth oauth-2.0 google-drive-api google-api-js-client


    【解决方案1】:

    您正在使用服务帐户执行上传

    按照您的操作方式,文件将上传到服务帐户驱动器 - 而不是您的驱动器。

    如果您想使用应该代表您执行操作的服务帐户执行上传(即将文件上传到您的驱动器),您需要使用impersonation

    在java中,在构建DRIVE_SERVICE时,必须添加一行

    .setServiceAccountId(emailAddress)

    指定服务帐户应代表其行事的用户的电子邮件地址(在本例中为您的电子邮件地址)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      相关资源
      最近更新 更多