繁体   English   中英

不使用OAuth将文件上传到Java中的Google驱动器

[英]Upload file to google drive in java without OAuth

我想将文件上传到Google云端硬盘中的帐户。 这个过程应该没有人为干预。 有什么方法可以使用提供我的用户名和密码的Google Drive API在我的Google Drive中上传文件吗?

到目前为止,我所做的是:

  • 我在https://console.developers.google.com中创建了一个项目,并启用了Google Drive API
  • https ://console.developers.google.com-> API和身份验证->凭据中,我创建了一个新的客户端ID,在应用程序类型中,我选择了服务帐户,并下载了pkcs12密钥。
  • 我有下一个代码:

     /** * Email of the Service Account */ private static final String SERVICE_ACCOUNT_EMAIL = "account_of_service_account@developer.gserviceaccount.com"; /** * Path to the Service Account's Private Key file */ private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "/path/to/pkcs12/donloaded.pkcs12"; /** * Build and returns a Drive service object authorized with the service * accounts. * * @return Drive service object that is ready to make requests. */ public static Drive getDriveService() throws GeneralSecurityException, IOException, URISyntaxException { HttpTransport httpTransport = new NetHttpTransport(); JacksonFactory jsonFactory = new JacksonFactory(); List<String> scopes = new ArrayList<String>(); scopes.add(DriveScopes.DRIVE); GoogleCredential credential; credential = new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(jsonFactory) .setServiceAccountId(SERVICE_ACCOUNT_EMAIL) .setServiceAccountScopes(scopes) .setServiceAccountPrivateKeyFromP12File(new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH)) .build(); Drive service = new Drive.Builder(httpTransport, jsonFactory, null) .setHttpRequestInitializer(credential).build(); return service; } public static void main(String[] args) throws GeneralSecurityException, IOException, URISyntaxException { Drive client = getDriveService(); File body = new File(); body.setTitle("mytitle"); body.setMimeType("application/vnd.google-apps.spreadsheet"); File file = client.files().insert(body).execute(); System.out.println(file.getId()); System.out.println(file.getAlternateLink()); } 

当我运行代码时,结果没问题,我得到了文件的ID和备用链接,但文件未加载到我的帐户中。 我将备用链接粘贴到浏览器中,但没有权限。

您刚刚上传的文件在哪里? 我应该更改些什么以指示最多我的帐户驱动器? 我应该在哪里添加要与驱动器关联的用户名和密码? 我应该如何对文件进行公开?

非常感谢您的关注。 我希望他们能帮助我。

您还需要在该项目上设置一个父项,例如“ root”,以便它们在“我的云端硬盘”空间中显示某人。 父级中的“ root”是用户界面中的“我的云端硬盘”。

在云端硬盘界面中使用搜索进行确认,您应该发现它们已经上传,但是由于您的代码未添加父项,因此当前处于“未父项”状态。

您正在将文件上传到服务帐户中。 如果您需要访问该文件,则必须与您的电子邮件共享。 使用以下方法与您的电子邮件共享文件。

 public static void shareFileOrFolder(Drive service, File file)
        throws IOException {
    Permission newPermission = new Permission();

    newPermission.setEmailAddress("xxxxx@gmail.com");
    newPermission.setValue("xxxxx@gmail.com");
    newPermission.setType("user");
    newPermission.setRole("writer");
    service.permissions().insert(file.getId(), newPermission).execute();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM